doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
class nntplib.NNTP(host, port=119, user=None, password=None, readermode=None, usenetrc=False[, timeout]) Return a new NNTP object, representing a connection to the NNTP server running on host host, listening at port port. An optional timeout can be specified for the socket connection. If the optional user and password are provided, or if suitable credentials are present in /.netrc and the optional flag usenetrc is true, the AUTHINFO USER and AUTHINFO PASS commands are used to identify and authenticate the user to the server. If the optional flag readermode is true, then a mode reader command is sent before authentication is performed. Reader mode is sometimes necessary if you are connecting to an NNTP server on the local machine and intend to call reader-specific commands, such as group. If you get unexpected NNTPPermanentErrors, you might need to set readermode. The NNTP class supports the with statement to unconditionally consume OSError exceptions and to close the NNTP connection when done, e.g.: >>> from nntplib import NNTP >>> with NNTP('news.gmane.io') as n: ... n.group('gmane.comp.python.committers') ... ('211 1755 1 1755 gmane.comp.python.committers', 1755, 1, 1755, 'gmane.comp.python.committers') >>> Raises an auditing event nntplib.connect with arguments self, host, port. All commands will raise an auditing event nntplib.putline with arguments self and line, where line is the bytes about to be sent to the remote host. Changed in version 3.2: usenetrc is now False by default. Changed in version 3.3: Support for the with statement was added. Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket.
python.library.nntplib#nntplib.NNTP
NNTP.article(message_spec=None, *, file=None) Send an ARTICLE command, where message_spec has the same meaning as for stat(). Return a tuple (response, info) where info is a namedtuple with three attributes number, message_id and lines (in that order). number is the article number in the group (or 0 if the information is not available), message_id the message id as a string, and lines a list of lines (without terminating newlines) comprising the raw message including headers and body. >>> resp, info = s.article('<20030112190404.GE29873@epoch.metaslash.com>') >>> info.number 0 >>> info.message_id '<20030112190404.GE29873@epoch.metaslash.com>' >>> len(info.lines) 65 >>> info.lines[0] b'Path: main.gmane.org!not-for-mail' >>> info.lines[1] b'From: Neal Norwitz <neal@metaslash.com>' >>> info.lines[-3:] [b'There is a patch for 2.3 as well as 2.2.', b'', b'Neal']
python.library.nntplib#nntplib.NNTP.article
NNTP.body(message_spec=None, *, file=None) Same as article(), but sends a BODY command. The lines returned (or written to file) will only contain the message body, not the headers.
python.library.nntplib#nntplib.NNTP.body
NNTP.date() Return a pair (response, date). date is a datetime object containing the current date and time of the server.
python.library.nntplib#nntplib.NNTP.date
NNTP.description(group) Get a description for a single group group. If more than one group matches (if ‘group’ is a real wildmat string), return the first match. If no group matches, return an empty string. This elides the response code from the server. If the response code is needed, use descriptions().
python.library.nntplib#nntplib.NNTP.description
NNTP.descriptions(grouppattern) Send a LIST NEWSGROUPS command, where grouppattern is a wildmat string as specified in RFC 3977 (it’s essentially the same as DOS or UNIX shell wildcard strings). Return a pair (response, descriptions), where descriptions is a dictionary mapping group names to textual descriptions. >>> resp, descs = s.descriptions('gmane.comp.python.*') >>> len(descs) 295 >>> descs.popitem() ('gmane.comp.python.bio.general', 'BioPython discussion list (Moderated)')
python.library.nntplib#nntplib.NNTP.descriptions
NNTP.getcapabilities() Return the RFC 3977 capabilities advertised by the server, as a dict instance mapping capability names to (possibly empty) lists of values. On legacy servers which don’t understand the CAPABILITIES command, an empty dictionary is returned instead. >>> s = NNTP('news.gmane.io') >>> 'POST' in s.getcapabilities() True New in version 3.2.
python.library.nntplib#nntplib.NNTP.getcapabilities
NNTP.getwelcome() Return the welcome message sent by the server in reply to the initial connection. (This message sometimes contains disclaimers or help information that may be relevant to the user.)
python.library.nntplib#nntplib.NNTP.getwelcome
NNTP.group(name) Send a GROUP command, where name is the group name. The group is selected as the current group, if it exists. Return a tuple (response, count, first, last, name) where count is the (estimated) number of articles in the group, first is the first article number in the group, last is the last article number in the group, and name is the group name.
python.library.nntplib#nntplib.NNTP.group
NNTP.head(message_spec=None, *, file=None) Same as article(), but sends a HEAD command. The lines returned (or written to file) will only contain the message headers, not the body.
python.library.nntplib#nntplib.NNTP.head
NNTP.help(*, file=None) Send a HELP command. Return a pair (response, list) where list is a list of help strings.
python.library.nntplib#nntplib.NNTP.help
NNTP.ihave(message_id, data) Send an IHAVE command. message_id is the id of the message to send to the server (enclosed in '<' and '>'). The data parameter and the return value are the same as for post().
python.library.nntplib#nntplib.NNTP.ihave
NNTP.last() Send a LAST command. Return as for stat().
python.library.nntplib#nntplib.NNTP.last
NNTP.list(group_pattern=None, *, file=None) Send a LIST or LIST ACTIVE command. Return a pair (response, list) where list is a list of tuples representing all the groups available from this NNTP server, optionally matching the pattern string group_pattern. Each tuple has the form (group, last, first, flag), where group is a group name, last and first are the last and first article numbers, and flag usually takes one of these values: y: Local postings and articles from peers are allowed. m: The group is moderated and all postings must be approved. n: No local postings are allowed, only articles from peers. j: Articles from peers are filed in the junk group instead. x: No local postings, and articles from peers are ignored. =foo.bar: Articles are filed in the foo.bar group instead. If flag has another value, then the status of the newsgroup should be considered unknown. This command can return very large results, especially if group_pattern is not specified. It is best to cache the results offline unless you really need to refresh them. Changed in version 3.2: group_pattern was added.
python.library.nntplib#nntplib.NNTP.list
NNTP.login(user=None, password=None, usenetrc=True) Send AUTHINFO commands with the user name and password. If user and password are None and usenetrc is true, credentials from ~/.netrc will be used if possible. Unless intentionally delayed, login is normally performed during the NNTP object initialization and separately calling this function is unnecessary. To force authentication to be delayed, you must not set user or password when creating the object, and must set usenetrc to False. New in version 3.2.
python.library.nntplib#nntplib.NNTP.login
NNTP.newgroups(date, *, file=None) Send a NEWGROUPS command. The date argument should be a datetime.date or datetime.datetime object. Return a pair (response, groups) where groups is a list representing the groups that are new since the given date. If file is supplied, though, then groups will be empty. >>> from datetime import date, timedelta >>> resp, groups = s.newgroups(date.today() - timedelta(days=3)) >>> len(groups) 85 >>> groups[0] GroupInfo(group='gmane.network.tor.devel', last='4', first='1', flag='m')
python.library.nntplib#nntplib.NNTP.newgroups
NNTP.newnews(group, date, *, file=None) Send a NEWNEWS command. Here, group is a group name or '*', and date has the same meaning as for newgroups(). Return a pair (response, articles) where articles is a list of message ids. This command is frequently disabled by NNTP server administrators.
python.library.nntplib#nntplib.NNTP.newnews
NNTP.next() Send a NEXT command. Return as for stat().
python.library.nntplib#nntplib.NNTP.next
NNTP.nntp_implementation A string describing the software name and version of the NNTP server, or None if not advertised by the server. New in version 3.2.
python.library.nntplib#nntplib.NNTP.nntp_implementation
NNTP.nntp_version An integer representing the version of the NNTP protocol supported by the server. In practice, this should be 2 for servers advertising RFC 3977 compliance and 1 for others. New in version 3.2.
python.library.nntplib#nntplib.NNTP.nntp_version
NNTP.over(message_spec, *, file=None) Send an OVER command, or an XOVER command on legacy servers. message_spec can be either a string representing a message id, or a (first, last) tuple of numbers indicating a range of articles in the current group, or a (first, None) tuple indicating a range of articles starting from first to the last article in the current group, or None to select the current article in the current group. Return a pair (response, overviews). overviews is a list of (article_number, overview) tuples, one for each article selected by message_spec. Each overview is a dictionary with the same number of items, but this number depends on the server. These items are either message headers (the key is then the lower-cased header name) or metadata items (the key is then the metadata name prepended with ":"). The following items are guaranteed to be present by the NNTP specification: the subject, from, date, message-id and references headers the :bytes metadata: the number of bytes in the entire raw article (including headers and body) the :lines metadata: the number of lines in the article body The value of each item is either a string, or None if not present. It is advisable to use the decode_header() function on header values when they may contain non-ASCII characters: >>> _, _, first, last, _ = s.group('gmane.comp.python.devel') >>> resp, overviews = s.over((last, last)) >>> art_num, over = overviews[0] >>> art_num 117216 >>> list(over.keys()) ['xref', 'from', ':lines', ':bytes', 'references', 'date', 'message-id', 'subject'] >>> over['from'] '=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?= <martin@v.loewis.de>' >>> nntplib.decode_header(over['from']) '"Martin v. Löwis" <martin@v.loewis.de>' New in version 3.2.
python.library.nntplib#nntplib.NNTP.over
NNTP.post(data) Post an article using the POST command. The data argument is either a file object opened for binary reading, or any iterable of bytes objects (representing raw lines of the article to be posted). It should represent a well-formed news article, including the required headers. The post() method automatically escapes lines beginning with . and appends the termination line. If the method succeeds, the server’s response is returned. If the server refuses posting, a NNTPReplyError is raised.
python.library.nntplib#nntplib.NNTP.post
NNTP.quit() Send a QUIT command and close the connection. Once this method has been called, no other methods of the NNTP object should be called.
python.library.nntplib#nntplib.NNTP.quit
NNTP.set_debuglevel(level) Set the instance’s debugging level. This controls the amount of debugging output printed. The default, 0, produces no debugging output. A value of 1 produces a moderate amount of debugging output, generally a single line per request or response. A value of 2 or higher produces the maximum amount of debugging output, logging each line sent and received on the connection (including message text).
python.library.nntplib#nntplib.NNTP.set_debuglevel
NNTP.slave() Send a SLAVE command. Return the server’s response.
python.library.nntplib#nntplib.NNTP.slave
NNTP.starttls(context=None) Send a STARTTLS command. This will enable encryption on the NNTP connection. The context argument is optional and should be a ssl.SSLContext object. Please read Security considerations for best practices. Note that this may not be done after authentication information has been transmitted, and authentication occurs by default if possible during a NNTP object initialization. See NNTP.login() for information on suppressing this behavior. New in version 3.2. Changed in version 3.4: The method now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).
python.library.nntplib#nntplib.NNTP.starttls
NNTP.stat(message_spec=None) Send a STAT command, where message_spec is either a message id (enclosed in '<' and '>') or an article number in the current group. If message_spec is omitted or None, the current article in the current group is considered. Return a triple (response, number, id) where number is the article number and id is the message id. >>> _, _, first, last, _ = s.group('gmane.comp.python.devel') >>> resp, number, message_id = s.stat(first) >>> number, message_id (9099, '<20030112190404.GE29873@epoch.metaslash.com>')
python.library.nntplib#nntplib.NNTP.stat
NNTP.xhdr(hdr, str, *, file=None) Send an XHDR command. The hdr argument is a header keyword, e.g. 'subject'. The str argument should have the form 'first-last' where first and last are the first and last article numbers to search. Return a pair (response, list), where list is a list of pairs (id, text), where id is an article number (as a string) and text is the text of the requested header for that article. If the file parameter is supplied, then the output of the XHDR command is stored in a file. If file is a string, then the method will open a file with that name, write to it then close it. If file is a file object, then it will start calling write() on it to store the lines of the command output. If file is supplied, then the returned list is an empty list.
python.library.nntplib#nntplib.NNTP.xhdr
NNTP.xover(start, end, *, file=None) Send an XOVER command. start and end are article numbers delimiting the range of articles to select. The return value is the same of for over(). It is recommended to use over() instead, since it will automatically use the newer OVER command if available.
python.library.nntplib#nntplib.NNTP.xover
exception nntplib.NNTPDataError Exception raised when there is some error in the response data.
python.library.nntplib#nntplib.NNTPDataError
exception nntplib.NNTPError Derived from the standard exception Exception, this is the base class for all exceptions raised by the nntplib module. Instances of this class have the following attribute: response The response of the server if available, as a str object.
python.library.nntplib#nntplib.NNTPError
response The response of the server if available, as a str object.
python.library.nntplib#nntplib.NNTPError.response
exception nntplib.NNTPPermanentError Exception raised when a response code in the range 500–599 is received.
python.library.nntplib#nntplib.NNTPPermanentError
exception nntplib.NNTPProtocolError Exception raised when a reply is received from the server that does not begin with a digit in the range 1–5.
python.library.nntplib#nntplib.NNTPProtocolError
exception nntplib.NNTPReplyError Exception raised when an unexpected reply is received from the server.
python.library.nntplib#nntplib.NNTPReplyError
exception nntplib.NNTPTemporaryError Exception raised when a response code in the range 400–499 is received.
python.library.nntplib#nntplib.NNTPTemporaryError
class nntplib.NNTP_SSL(host, port=563, user=None, password=None, ssl_context=None, readermode=None, usenetrc=False[, timeout]) Return a new NNTP_SSL object, representing an encrypted connection to the NNTP server running on host host, listening at port port. NNTP_SSL objects have the same methods as NNTP objects. If port is omitted, port 563 (NNTPS) is used. ssl_context is also optional, and is a SSLContext object. Please read Security considerations for best practices. All other parameters behave the same as for NNTP. Note that SSL-on-563 is discouraged per RFC 4642, in favor of STARTTLS as described below. However, some servers only support the former. Raises an auditing event nntplib.connect with arguments self, host, port. All commands will raise an auditing event nntplib.putline with arguments self and line, where line is the bytes about to be sent to the remote host. New in version 3.2. Changed in version 3.4: The class now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI). Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket.
python.library.nntplib#nntplib.NNTP_SSL
None The sole value of the type NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to None are illegal and raise a SyntaxError.
python.library.constants#None
exception NotADirectoryError Raised when a directory operation (such as os.listdir()) is requested on something which is not a directory. Corresponds to errno ENOTDIR.
python.library.exceptions#NotADirectoryError
NotImplemented Special value which should be returned by the binary special methods (e.g. __eq__(), __lt__(), __add__(), __rsub__(), etc.) to indicate that the operation is not implemented with respect to the other type; may be returned by the in-place binary special methods (e.g. __imul__(), __iand__(), etc.) for the same purpose. It should not be evaluated in a boolean context. Note When a binary (or in-place) method returns NotImplemented the interpreter will try the reflected operation on the other type (or some other fallback, depending on the operator). If all attempts return NotImplemented, the interpreter will raise an appropriate exception. Incorrectly returning NotImplemented will result in a misleading error message or the NotImplemented value being returned to Python code. See Implementing the arithmetic operations for examples. Note NotImplementedError and NotImplemented are not interchangeable, even though they have similar names and purposes. See NotImplementedError for details on when to use it. Changed in version 3.9: Evaluating NotImplemented in a boolean context is deprecated. While it currently evaluates as true, it will emit a DeprecationWarning. It will raise a TypeError in a future version of Python.
python.library.constants#NotImplemented
exception NotImplementedError This exception is derived from RuntimeError. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method, or while the class is being developed to indicate that the real implementation still needs to be added. Note It should not be used to indicate that an operator or method is not meant to be supported at all – in that case either leave the operator / method undefined or, if a subclass, set it to None. Note NotImplementedError and NotImplemented are not interchangeable, even though they have similar names and purposes. See NotImplemented for details on when to use it.
python.library.exceptions#NotImplementedError
numbers — Numeric abstract base classes Source code: Lib/numbers.py The numbers module (PEP 3141) defines a hierarchy of numeric abstract base classes which progressively define more operations. None of the types defined in this module can be instantiated. class numbers.Number The root of the numeric hierarchy. If you just want to check if an argument x is a number, without caring what kind, use isinstance(x, Number). The numeric tower class numbers.Complex Subclasses of this type describe complex numbers and include the operations that work on the built-in complex type. These are: conversions to complex and bool, real, imag, +, -, *, /, abs(), conjugate(), ==, and !=. All except - and != are abstract. real Abstract. Retrieves the real component of this number. imag Abstract. Retrieves the imaginary component of this number. abstractmethod conjugate() Abstract. Returns the complex conjugate. For example, (1+3j).conjugate() == (1-3j). class numbers.Real To Complex, Real adds the operations that work on real numbers. In short, those are: a conversion to float, math.trunc(), round(), math.floor(), math.ceil(), divmod(), //, %, <, <=, >, and >=. Real also provides defaults for complex(), real, imag, and conjugate(). class numbers.Rational Subtypes Real and adds numerator and denominator properties, which should be in lowest terms. With these, it provides a default for float(). numerator Abstract. denominator Abstract. class numbers.Integral Subtypes Rational and adds a conversion to int. Provides defaults for float(), numerator, and denominator. Adds abstract methods for ** and bit-string operations: <<, >>, &, ^, |, ~. Notes for type implementors Implementors should be careful to make equal numbers equal and hash them to the same values. This may be subtle if there are two different extensions of the real numbers. For example, fractions.Fraction implements hash() as follows: def __hash__(self): if self.denominator == 1: # Get integers right. return hash(self.numerator) # Expensive check, but definitely correct. if self == float(self): return hash(float(self)) else: # Use tuple's hash to avoid a high collision rate on # simple fractions. return hash((self.numerator, self.denominator)) Adding More Numeric ABCs There are, of course, more possible ABCs for numbers, and this would be a poor hierarchy if it precluded the possibility of adding those. You can add MyFoo between Complex and Real with: class MyFoo(Complex): ... MyFoo.register(Real) Implementing the arithmetic operations We want to implement the arithmetic operations so that mixed-mode operations either call an implementation whose author knew about the types of both arguments, or convert both to the nearest built in type and do the operation there. For subtypes of Integral, this means that __add__() and __radd__() should be defined as: class MyIntegral(Integral): def __add__(self, other): if isinstance(other, MyIntegral): return do_my_adding_stuff(self, other) elif isinstance(other, OtherTypeIKnowAbout): return do_my_other_adding_stuff(self, other) else: return NotImplemented def __radd__(self, other): if isinstance(other, MyIntegral): return do_my_adding_stuff(other, self) elif isinstance(other, OtherTypeIKnowAbout): return do_my_other_adding_stuff(other, self) elif isinstance(other, Integral): return int(other) + int(self) elif isinstance(other, Real): return float(other) + float(self) elif isinstance(other, Complex): return complex(other) + complex(self) else: return NotImplemented There are 5 different cases for a mixed-type operation on subclasses of Complex. I’ll refer to all of the above code that doesn’t refer to MyIntegral and OtherTypeIKnowAbout as “boilerplate”. a will be an instance of A, which is a subtype of Complex (a : A <: Complex), and b : B <: Complex. I’ll consider a + b: If A defines an __add__() which accepts b, all is well. If A falls back to the boilerplate code, and it were to return a value from __add__(), we’d miss the possibility that B defines a more intelligent __radd__(), so the boilerplate should return NotImplemented from __add__(). (Or A may not implement __add__() at all.) Then B’s __radd__() gets a chance. If it accepts a, all is well. If it falls back to the boilerplate, there are no more possible methods to try, so this is where the default implementation should live. If B <: A, Python tries B.__radd__ before A.__add__. This is ok, because it was implemented with knowledge of A, so it can handle those instances before delegating to Complex. If A <: Complex and B <: Real without sharing any other knowledge, then the appropriate shared operation is the one involving the built in complex, and both __radd__() s land there, so a+b == b+a. Because most of the operations on any given type will be very similar, it can be useful to define a helper function which generates the forward and reverse instances of any given operator. For example, fractions.Fraction uses: def _operator_fallbacks(monomorphic_operator, fallback_operator): def forward(a, b): if isinstance(b, (int, Fraction)): return monomorphic_operator(a, b) elif isinstance(b, float): return fallback_operator(float(a), b) elif isinstance(b, complex): return fallback_operator(complex(a), b) else: return NotImplemented forward.__name__ = '__' + fallback_operator.__name__ + '__' forward.__doc__ = monomorphic_operator.__doc__ def reverse(b, a): if isinstance(a, Rational): # Includes ints. return monomorphic_operator(a, b) elif isinstance(a, numbers.Real): return fallback_operator(float(a), float(b)) elif isinstance(a, numbers.Complex): return fallback_operator(complex(a), complex(b)) else: return NotImplemented reverse.__name__ = '__r' + fallback_operator.__name__ + '__' reverse.__doc__ = monomorphic_operator.__doc__ return forward, reverse def _add(a, b): """a + b""" return Fraction(a.numerator * b.denominator + b.numerator * a.denominator, a.denominator * b.denominator) __add__, __radd__ = _operator_fallbacks(_add, operator.add) # ...
python.library.numbers
class numbers.Complex Subclasses of this type describe complex numbers and include the operations that work on the built-in complex type. These are: conversions to complex and bool, real, imag, +, -, *, /, abs(), conjugate(), ==, and !=. All except - and != are abstract. real Abstract. Retrieves the real component of this number. imag Abstract. Retrieves the imaginary component of this number. abstractmethod conjugate() Abstract. Returns the complex conjugate. For example, (1+3j).conjugate() == (1-3j).
python.library.numbers#numbers.Complex
abstractmethod conjugate() Abstract. Returns the complex conjugate. For example, (1+3j).conjugate() == (1-3j).
python.library.numbers#numbers.Complex.conjugate
imag Abstract. Retrieves the imaginary component of this number.
python.library.numbers#numbers.Complex.imag
real Abstract. Retrieves the real component of this number.
python.library.numbers#numbers.Complex.real
class numbers.Integral Subtypes Rational and adds a conversion to int. Provides defaults for float(), numerator, and denominator. Adds abstract methods for ** and bit-string operations: <<, >>, &, ^, |, ~.
python.library.numbers#numbers.Integral
class numbers.Number The root of the numeric hierarchy. If you just want to check if an argument x is a number, without caring what kind, use isinstance(x, Number).
python.library.numbers#numbers.Number
class numbers.Rational Subtypes Real and adds numerator and denominator properties, which should be in lowest terms. With these, it provides a default for float(). numerator Abstract. denominator Abstract.
python.library.numbers#numbers.Rational
denominator Abstract.
python.library.numbers#numbers.Rational.denominator
numerator Abstract.
python.library.numbers#numbers.Rational.numerator
class numbers.Real To Complex, Real adds the operations that work on real numbers. In short, those are: a conversion to float, math.trunc(), round(), math.floor(), math.ceil(), divmod(), //, %, <, <=, >, and >=. Real also provides defaults for complex(), real, imag, and conjugate().
python.library.numbers#numbers.Real
class object Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments. Note object does not have a __dict__, so you can’t assign arbitrary attributes to an instance of the object class.
python.library.functions#object
object.__dict__ A dictionary or other mapping object used to store an object’s (writable) attributes.
python.library.stdtypes#object.__dict__
object.__getnewargs_ex__() In protocols 2 and newer, classes that implements the __getnewargs_ex__() method can dictate the values passed to the __new__() method upon unpickling. The method must return a pair (args, kwargs) where args is a tuple of positional arguments and kwargs a dictionary of named arguments for constructing the object. Those will be passed to the __new__() method upon unpickling. You should implement this method if the __new__() method of your class requires keyword-only arguments. Otherwise, it is recommended for compatibility to implement __getnewargs__(). Changed in version 3.6: __getnewargs_ex__() is now used in protocols 2 and 3.
python.library.pickle#object.__getnewargs_ex__
object.__getnewargs__() This method serves a similar purpose as __getnewargs_ex__(), but supports only positional arguments. It must return a tuple of arguments args which will be passed to the __new__() method upon unpickling. __getnewargs__() will not be called if __getnewargs_ex__() is defined. Changed in version 3.6: Before Python 3.6, __getnewargs__() was called instead of __getnewargs_ex__() in protocols 2 and 3.
python.library.pickle#object.__getnewargs__
object.__getstate__() Classes can further influence how their instances are pickled; if the class defines the method __getstate__(), it is called and the returned object is pickled as the contents for the instance, instead of the contents of the instance’s dictionary. If the __getstate__() method is absent, the instance’s __dict__ is pickled as usual.
python.library.pickle#object.__getstate__
object.__reduce_ex__(protocol) Alternatively, a __reduce_ex__() method may be defined. The only difference is this method should take a single integer argument, the protocol version. When defined, pickle will prefer it over the __reduce__() method. In addition, __reduce__() automatically becomes a synonym for the extended version. The main use for this method is to provide backwards-compatible reduce values for older Python releases.
python.library.pickle#object.__reduce_ex__
object.__reduce__() The interface is currently defined as follows. The __reduce__() method takes no argument and shall return either a string or preferably a tuple (the returned object is often referred to as the “reduce value”). If a string is returned, the string should be interpreted as the name of a global variable. It should be the object’s local name relative to its module; the pickle module searches the module namespace to determine the object’s module. This behaviour is typically useful for singletons. When a tuple is returned, it must be between two and six items long. Optional items can either be omitted, or None can be provided as their value. The semantics of each item are in order: A callable object that will be called to create the initial version of the object. A tuple of arguments for the callable object. An empty tuple must be given if the callable does not accept any argument. Optionally, the object’s state, which will be passed to the object’s __setstate__() method as previously described. If the object has no such method then, the value must be a dictionary and it will be added to the object’s __dict__ attribute. Optionally, an iterator (and not a sequence) yielding successive items. These items will be appended to the object either using obj.append(item) or, in batch, using obj.extend(list_of_items). This is primarily used for list subclasses, but may be used by other classes as long as they have append() and extend() methods with the appropriate signature. (Whether append() or extend() is used depends on which pickle protocol version is used as well as the number of items to append, so both must be supported.) Optionally, an iterator (not a sequence) yielding successive key-value pairs. These items will be stored to the object using obj[key] = value. This is primarily used for dictionary subclasses, but may be used by other classes as long as they implement __setitem__(). Optionally, a callable with a (obj, state) signature. This callable allows the user to programmatically control the state-updating behavior of a specific object, instead of using obj’s static __setstate__() method. If not None, this callable will have priority over obj’s __setstate__(). New in version 3.8: The optional sixth tuple item, (obj, state), was added.
python.library.pickle#object.__reduce__
object.__setstate__(state) Upon unpickling, if the class defines __setstate__(), it is called with the unpickled state. In that case, there is no requirement for the state object to be a dictionary. Otherwise, the pickled state must be a dictionary and its items are assigned to the new instance’s dictionary. Note If __getstate__() returns a false value, the __setstate__() method will not be called upon unpickling.
python.library.pickle#object.__setstate__
oct(x) Convert an integer number to an octal string prefixed with “0o”. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. For example: >>> oct(8) '0o10' >>> oct(-56) '-0o70' If you want to convert an integer number to octal string either with prefix “0o” or not, you can use either of the following ways. >>> '%#o' % 10, '%o' % 10 ('0o12', '12') >>> format(10, '#o'), format(10, 'o') ('0o12', '12') >>> f'{10:#o}', f'{10:o}' ('0o12', '12') See also format() for more information.
python.library.functions#oct
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised. See Reading and Writing Files for more examples of how to use this function. file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.) mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are: Character Meaning 'r' open for reading (default) 'w' open for writing, truncating the file first 'x' open for exclusive creation, failing if the file already exists 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open for updating (reading and writing) The default mode is 'r' (open for reading text, synonym of 'rt'). Modes 'w+' and 'w+b' open and truncate the file. Modes 'r+' and 'r+b' open the file with no truncation. As mentioned in the Overview, Python distinguishes between binary and text I/O. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given. There is an additional mode character permitted, 'U', which no longer has any effect, and is considered deprecated. It previously enabled universal newlines in text mode, which became the default behaviour in Python 3.0. Refer to the documentation of the newline parameter for further details. Note Python doesn’t depend on the underlying operating system’s notion of text files; all the processing is done by Python itself, and is therefore platform-independent. buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows: Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long. “Interactive” text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files. encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings. errors is an optional string that specifies how encoding and decoding errors are to be handled—this cannot be used in binary mode. A variety of standard error handlers are available (listed under Error Handlers), though any error handling name that has been registered with codecs.register_error() is also valid. The standard names include: 'strict' to raise a ValueError exception if there is an encoding error. The default value of None has the same effect. 'ignore' ignores errors. Note that ignoring encoding errors can lead to data loss. 'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data. 'surrogateescape' will represent any incorrect bytes as code points in the Unicode Private Use Area ranging from U+DC80 to U+DCFF. These private code points will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding. 'xmlcharrefreplace' is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference &#nnn;. 'backslashreplace' replaces malformed data by Python’s backslashed escape sequences. 'namereplace' (also only supported when writing) replaces unsupported characters with \N{...} escape sequences. newline controls how universal newlines mode works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows: When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. If closefd is False and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd must be True (the default) otherwise an error will be raised. A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (file, flags). opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None). The newly created file is non-inheritable. The following example uses the dir_fd parameter of the os.open() function to open a file relative to a given directory: >>> import os >>> dir_fd = os.open('somedir', os.O_RDONLY) >>> def opener(path, flags): ... return os.open(path, flags, dir_fd=dir_fd) ... >>> with open('spamspam.txt', 'w', opener=opener) as f: ... print('This will be written to somedir/spamspam.txt', file=f) ... >>> os.close(dir_fd) # don't leak a file descriptor The type of file object returned by the open() function depends on the mode. When open() is used to open a file in a text mode ('w', 'r', 'wt', 'rt', etc.), it returns a subclass of io.TextIOBase (specifically io.TextIOWrapper). When used to open a file in a binary mode with buffering, the returned class is a subclass of io.BufferedIOBase. The exact class varies: in read binary mode, it returns an io.BufferedReader; in write binary and append binary modes, it returns an io.BufferedWriter, and in read/write mode, it returns an io.BufferedRandom. When buffering is disabled, the raw stream, a subclass of io.RawIOBase, io.FileIO, is returned. See also the file handling modules, such as, fileinput, io (where open() is declared), os, os.path, tempfile, and shutil. Raises an auditing event open with arguments file, mode, flags. The mode and flags arguments may have been modified or inferred from the original call. Changed in version 3.3: The opener parameter was added. The 'x' mode was added. IOError used to be raised, it is now an alias of OSError. FileExistsError is now raised if the file opened in exclusive creation mode ('x') already exists. Changed in version 3.4: The file is now non-inheritable. Deprecated since version 3.4, will be removed in version 3.10: The 'U' mode. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale). The 'namereplace' error handler was added. Changed in version 3.6: Support added to accept objects implementing os.PathLike. On Windows, opening a console buffer may return a subclass of io.RawIOBase other than io.FileIO.
python.library.functions#open
BaseHandler.<protocol>_open(req) This method is not defined in BaseHandler, but subclasses should define it if they want to handle URLs with the given protocol. This method, if defined, will be called by the parent OpenerDirector. Return values should be the same as for default_open().
python.library.urllib.request#open
operator — Standard operators as functions Source code: Lib/operator.py The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y. Many function names are those used for special methods, without the double underscores. For backward compatibility, many of these have a variant with the double underscores kept. The variants without the double underscores are preferred for clarity. The functions fall into categories that perform object comparisons, logical operations, mathematical operations and sequence operations. The object comparison functions are useful for all objects, and are named after the rich comparison operators they support: operator.lt(a, b) operator.le(a, b) operator.eq(a, b) operator.ne(a, b) operator.ge(a, b) operator.gt(a, b) operator.__lt__(a, b) operator.__le__(a, b) operator.__eq__(a, b) operator.__ne__(a, b) operator.__ge__(a, b) operator.__gt__(a, b) Perform “rich comparisons” between a and b. Specifically, lt(a, b) is equivalent to a < b, le(a, b) is equivalent to a <= b, eq(a, b) is equivalent to a == b, ne(a, b) is equivalent to a != b, gt(a, b) is equivalent to a > b and ge(a, b) is equivalent to a >= b. Note that these functions can return any value, which may or may not be interpretable as a Boolean value. See Comparisons for more information about rich comparisons. The logical operations are also generally applicable to all objects, and support truth tests, identity tests, and boolean operations: operator.not_(obj) operator.__not__(obj) Return the outcome of not obj. (Note that there is no __not__() method for object instances; only the interpreter core defines this operation. The result is affected by the __bool__() and __len__() methods.) operator.truth(obj) Return True if obj is true, and False otherwise. This is equivalent to using the bool constructor. operator.is_(a, b) Return a is b. Tests object identity. operator.is_not(a, b) Return a is not b. Tests object identity. The mathematical and bitwise operations are the most numerous: operator.abs(obj) operator.__abs__(obj) Return the absolute value of obj. operator.add(a, b) operator.__add__(a, b) Return a + b, for a and b numbers. operator.and_(a, b) operator.__and__(a, b) Return the bitwise and of a and b. operator.floordiv(a, b) operator.__floordiv__(a, b) Return a // b. operator.index(a) operator.__index__(a) Return a converted to an integer. Equivalent to a.__index__(). operator.inv(obj) operator.invert(obj) operator.__inv__(obj) operator.__invert__(obj) Return the bitwise inverse of the number obj. This is equivalent to ~obj. operator.lshift(a, b) operator.__lshift__(a, b) Return a shifted left by b. operator.mod(a, b) operator.__mod__(a, b) Return a % b. operator.mul(a, b) operator.__mul__(a, b) Return a * b, for a and b numbers. operator.matmul(a, b) operator.__matmul__(a, b) Return a @ b. New in version 3.5. operator.neg(obj) operator.__neg__(obj) Return obj negated (-obj). operator.or_(a, b) operator.__or__(a, b) Return the bitwise or of a and b. operator.pos(obj) operator.__pos__(obj) Return obj positive (+obj). operator.pow(a, b) operator.__pow__(a, b) Return a ** b, for a and b numbers. operator.rshift(a, b) operator.__rshift__(a, b) Return a shifted right by b. operator.sub(a, b) operator.__sub__(a, b) Return a - b. operator.truediv(a, b) operator.__truediv__(a, b) Return a / b where 2/3 is .66 rather than 0. This is also known as “true” division. operator.xor(a, b) operator.__xor__(a, b) Return the bitwise exclusive or of a and b. Operations which work with sequences (some of them with mappings too) include: operator.concat(a, b) operator.__concat__(a, b) Return a + b for a and b sequences. operator.contains(a, b) operator.__contains__(a, b) Return the outcome of the test b in a. Note the reversed operands. operator.countOf(a, b) Return the number of occurrences of b in a. operator.delitem(a, b) operator.__delitem__(a, b) Remove the value of a at index b. operator.getitem(a, b) operator.__getitem__(a, b) Return the value of a at index b. operator.indexOf(a, b) Return the index of the first of occurrence of b in a. operator.setitem(a, b, c) operator.__setitem__(a, b, c) Set the value of a at index b to c. operator.length_hint(obj, default=0) Return an estimated length for the object o. First try to return its actual length, then an estimate using object.__length_hint__(), and finally return the default value. New in version 3.4. The operator module also defines tools for generalized attribute and item lookups. These are useful for making fast field extractors as arguments for map(), sorted(), itertools.groupby(), or other functions that expect a function argument. operator.attrgetter(attr) operator.attrgetter(*attrs) Return a callable object that fetches attr from its operand. If more than one attribute is requested, returns a tuple of attributes. The attribute names can also contain dots. For example: After f = attrgetter('name'), the call f(b) returns b.name. After f = attrgetter('name', 'date'), the call f(b) returns (b.name, b.date). After f = attrgetter('name.first', 'name.last'), the call f(b) returns (b.name.first, b.name.last). Equivalent to: def attrgetter(*items): if any(not isinstance(item, str) for item in items): raise TypeError('attribute name must be a string') if len(items) == 1: attr = items[0] def g(obj): return resolve_attr(obj, attr) else: def g(obj): return tuple(resolve_attr(obj, attr) for attr in items) return g def resolve_attr(obj, attr): for name in attr.split("."): obj = getattr(obj, name) return obj operator.itemgetter(item) operator.itemgetter(*items) Return a callable object that fetches item from its operand using the operand’s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example: After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]). Equivalent to: def itemgetter(*items): if len(items) == 1: item = items[0] def g(obj): return obj[item] else: def g(obj): return tuple(obj[item] for item in items) return g The items can be any type accepted by the operand’s __getitem__() method. Dictionaries accept any hashable value. Lists, tuples, and strings accept an index or a slice: >>> itemgetter(1)('ABCDEFG') 'B' >>> itemgetter(1, 3, 5)('ABCDEFG') ('B', 'D', 'F') >>> itemgetter(slice(2, None))('ABCDEFG') 'CDEFG' >>> soldier = dict(rank='captain', name='dotterbart') >>> itemgetter('rank')(soldier) 'captain' Example of using itemgetter() to retrieve specific fields from a tuple record: >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)] >>> getcount = itemgetter(1) >>> list(map(getcount, inventory)) [3, 2, 5, 1] >>> sorted(inventory, key=getcount) [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)] operator.methodcaller(name, /, *args, **kwargs) Return a callable object that calls the method name on its operand. If additional arguments and/or keyword arguments are given, they will be given to the method as well. For example: After f = methodcaller('name'), the call f(b) returns b.name(). After f = methodcaller('name', 'foo', bar=1), the call f(b) returns b.name('foo', bar=1). Equivalent to: def methodcaller(name, /, *args, **kwargs): def caller(obj): return getattr(obj, name)(*args, **kwargs) return caller Mapping Operators to Functions This table shows how abstract operations correspond to operator symbols in the Python syntax and the functions in the operator module. Operation Syntax Function Addition a + b add(a, b) Concatenation seq1 + seq2 concat(seq1, seq2) Containment Test obj in seq contains(seq, obj) Division a / b truediv(a, b) Division a // b floordiv(a, b) Bitwise And a & b and_(a, b) Bitwise Exclusive Or a ^ b xor(a, b) Bitwise Inversion ~ a invert(a) Bitwise Or a | b or_(a, b) Exponentiation a ** b pow(a, b) Identity a is b is_(a, b) Identity a is not b is_not(a, b) Indexed Assignment obj[k] = v setitem(obj, k, v) Indexed Deletion del obj[k] delitem(obj, k) Indexing obj[k] getitem(obj, k) Left Shift a << b lshift(a, b) Modulo a % b mod(a, b) Multiplication a * b mul(a, b) Matrix Multiplication a @ b matmul(a, b) Negation (Arithmetic) - a neg(a) Negation (Logical) not a not_(a) Positive + a pos(a) Right Shift a >> b rshift(a, b) Slice Assignment seq[i:j] = values setitem(seq, slice(i, j), values) Slice Deletion del seq[i:j] delitem(seq, slice(i, j)) Slicing seq[i:j] getitem(seq, slice(i, j)) String Formatting s % obj mod(s, obj) Subtraction a - b sub(a, b) Truth Test obj truth(obj) Ordering a < b lt(a, b) Ordering a <= b le(a, b) Equality a == b eq(a, b) Difference a != b ne(a, b) Ordering a >= b ge(a, b) Ordering a > b gt(a, b) In-place Operators Many operations have an “in-place” version. Listed below are functions providing a more primitive access to in-place operators than the usual syntax does; for example, the statement x += y is equivalent to x = operator.iadd(x, y). Another way to put it is to say that z = operator.iadd(x, y) is equivalent to the compound statement z = x; z += y. In those examples, note that when an in-place method is called, the computation and assignment are performed in two separate steps. The in-place functions listed below only do the first step, calling the in-place method. The second step, assignment, is not handled. For immutable targets such as strings, numbers, and tuples, the updated value is computed, but not assigned back to the input variable: >>> a = 'hello' >>> iadd(a, ' world') 'hello world' >>> a 'hello' For mutable targets such as lists and dictionaries, the in-place method will perform the update, so no subsequent assignment is necessary: >>> s = ['h', 'e', 'l', 'l', 'o'] >>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd']) ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] >>> s ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] operator.iadd(a, b) operator.__iadd__(a, b) a = iadd(a, b) is equivalent to a += b. operator.iand(a, b) operator.__iand__(a, b) a = iand(a, b) is equivalent to a &= b. operator.iconcat(a, b) operator.__iconcat__(a, b) a = iconcat(a, b) is equivalent to a += b for a and b sequences. operator.ifloordiv(a, b) operator.__ifloordiv__(a, b) a = ifloordiv(a, b) is equivalent to a //= b. operator.ilshift(a, b) operator.__ilshift__(a, b) a = ilshift(a, b) is equivalent to a <<= b. operator.imod(a, b) operator.__imod__(a, b) a = imod(a, b) is equivalent to a %= b. operator.imul(a, b) operator.__imul__(a, b) a = imul(a, b) is equivalent to a *= b. operator.imatmul(a, b) operator.__imatmul__(a, b) a = imatmul(a, b) is equivalent to a @= b. New in version 3.5. operator.ior(a, b) operator.__ior__(a, b) a = ior(a, b) is equivalent to a |= b. operator.ipow(a, b) operator.__ipow__(a, b) a = ipow(a, b) is equivalent to a **= b. operator.irshift(a, b) operator.__irshift__(a, b) a = irshift(a, b) is equivalent to a >>= b. operator.isub(a, b) operator.__isub__(a, b) a = isub(a, b) is equivalent to a -= b. operator.itruediv(a, b) operator.__itruediv__(a, b) a = itruediv(a, b) is equivalent to a /= b. operator.ixor(a, b) operator.__ixor__(a, b) a = ixor(a, b) is equivalent to a ^= b.
python.library.operator
operator.abs(obj) operator.__abs__(obj) Return the absolute value of obj.
python.library.operator#operator.abs
operator.add(a, b) operator.__add__(a, b) Return a + b, for a and b numbers.
python.library.operator#operator.add
operator.and_(a, b) operator.__and__(a, b) Return the bitwise and of a and b.
python.library.operator#operator.and_
operator.attrgetter(attr) operator.attrgetter(*attrs) Return a callable object that fetches attr from its operand. If more than one attribute is requested, returns a tuple of attributes. The attribute names can also contain dots. For example: After f = attrgetter('name'), the call f(b) returns b.name. After f = attrgetter('name', 'date'), the call f(b) returns (b.name, b.date). After f = attrgetter('name.first', 'name.last'), the call f(b) returns (b.name.first, b.name.last). Equivalent to: def attrgetter(*items): if any(not isinstance(item, str) for item in items): raise TypeError('attribute name must be a string') if len(items) == 1: attr = items[0] def g(obj): return resolve_attr(obj, attr) else: def g(obj): return tuple(resolve_attr(obj, attr) for attr in items) return g def resolve_attr(obj, attr): for name in attr.split("."): obj = getattr(obj, name) return obj
python.library.operator#operator.attrgetter
operator.concat(a, b) operator.__concat__(a, b) Return a + b for a and b sequences.
python.library.operator#operator.concat
operator.contains(a, b) operator.__contains__(a, b) Return the outcome of the test b in a. Note the reversed operands.
python.library.operator#operator.contains
operator.countOf(a, b) Return the number of occurrences of b in a.
python.library.operator#operator.countOf
operator.delitem(a, b) operator.__delitem__(a, b) Remove the value of a at index b.
python.library.operator#operator.delitem
operator.lt(a, b) operator.le(a, b) operator.eq(a, b) operator.ne(a, b) operator.ge(a, b) operator.gt(a, b) operator.__lt__(a, b) operator.__le__(a, b) operator.__eq__(a, b) operator.__ne__(a, b) operator.__ge__(a, b) operator.__gt__(a, b) Perform “rich comparisons” between a and b. Specifically, lt(a, b) is equivalent to a < b, le(a, b) is equivalent to a <= b, eq(a, b) is equivalent to a == b, ne(a, b) is equivalent to a != b, gt(a, b) is equivalent to a > b and ge(a, b) is equivalent to a >= b. Note that these functions can return any value, which may or may not be interpretable as a Boolean value. See Comparisons for more information about rich comparisons.
python.library.operator#operator.eq
operator.floordiv(a, b) operator.__floordiv__(a, b) Return a // b.
python.library.operator#operator.floordiv
operator.lt(a, b) operator.le(a, b) operator.eq(a, b) operator.ne(a, b) operator.ge(a, b) operator.gt(a, b) operator.__lt__(a, b) operator.__le__(a, b) operator.__eq__(a, b) operator.__ne__(a, b) operator.__ge__(a, b) operator.__gt__(a, b) Perform “rich comparisons” between a and b. Specifically, lt(a, b) is equivalent to a < b, le(a, b) is equivalent to a <= b, eq(a, b) is equivalent to a == b, ne(a, b) is equivalent to a != b, gt(a, b) is equivalent to a > b and ge(a, b) is equivalent to a >= b. Note that these functions can return any value, which may or may not be interpretable as a Boolean value. See Comparisons for more information about rich comparisons.
python.library.operator#operator.ge
operator.getitem(a, b) operator.__getitem__(a, b) Return the value of a at index b.
python.library.operator#operator.getitem
operator.lt(a, b) operator.le(a, b) operator.eq(a, b) operator.ne(a, b) operator.ge(a, b) operator.gt(a, b) operator.__lt__(a, b) operator.__le__(a, b) operator.__eq__(a, b) operator.__ne__(a, b) operator.__ge__(a, b) operator.__gt__(a, b) Perform “rich comparisons” between a and b. Specifically, lt(a, b) is equivalent to a < b, le(a, b) is equivalent to a <= b, eq(a, b) is equivalent to a == b, ne(a, b) is equivalent to a != b, gt(a, b) is equivalent to a > b and ge(a, b) is equivalent to a >= b. Note that these functions can return any value, which may or may not be interpretable as a Boolean value. See Comparisons for more information about rich comparisons.
python.library.operator#operator.gt
operator.iadd(a, b) operator.__iadd__(a, b) a = iadd(a, b) is equivalent to a += b.
python.library.operator#operator.iadd
operator.iand(a, b) operator.__iand__(a, b) a = iand(a, b) is equivalent to a &= b.
python.library.operator#operator.iand
operator.iconcat(a, b) operator.__iconcat__(a, b) a = iconcat(a, b) is equivalent to a += b for a and b sequences.
python.library.operator#operator.iconcat
operator.ifloordiv(a, b) operator.__ifloordiv__(a, b) a = ifloordiv(a, b) is equivalent to a //= b.
python.library.operator#operator.ifloordiv
operator.ilshift(a, b) operator.__ilshift__(a, b) a = ilshift(a, b) is equivalent to a <<= b.
python.library.operator#operator.ilshift
operator.imatmul(a, b) operator.__imatmul__(a, b) a = imatmul(a, b) is equivalent to a @= b. New in version 3.5.
python.library.operator#operator.imatmul
operator.imod(a, b) operator.__imod__(a, b) a = imod(a, b) is equivalent to a %= b.
python.library.operator#operator.imod
operator.imul(a, b) operator.__imul__(a, b) a = imul(a, b) is equivalent to a *= b.
python.library.operator#operator.imul
operator.index(a) operator.__index__(a) Return a converted to an integer. Equivalent to a.__index__().
python.library.operator#operator.index
operator.indexOf(a, b) Return the index of the first of occurrence of b in a.
python.library.operator#operator.indexOf
operator.inv(obj) operator.invert(obj) operator.__inv__(obj) operator.__invert__(obj) Return the bitwise inverse of the number obj. This is equivalent to ~obj.
python.library.operator#operator.inv
operator.inv(obj) operator.invert(obj) operator.__inv__(obj) operator.__invert__(obj) Return the bitwise inverse of the number obj. This is equivalent to ~obj.
python.library.operator#operator.invert
operator.ior(a, b) operator.__ior__(a, b) a = ior(a, b) is equivalent to a |= b.
python.library.operator#operator.ior
operator.ipow(a, b) operator.__ipow__(a, b) a = ipow(a, b) is equivalent to a **= b.
python.library.operator#operator.ipow
operator.irshift(a, b) operator.__irshift__(a, b) a = irshift(a, b) is equivalent to a >>= b.
python.library.operator#operator.irshift
operator.isub(a, b) operator.__isub__(a, b) a = isub(a, b) is equivalent to a -= b.
python.library.operator#operator.isub
operator.is_(a, b) Return a is b. Tests object identity.
python.library.operator#operator.is_
operator.is_not(a, b) Return a is not b. Tests object identity.
python.library.operator#operator.is_not
operator.itemgetter(item) operator.itemgetter(*items) Return a callable object that fetches item from its operand using the operand’s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example: After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]). Equivalent to: def itemgetter(*items): if len(items) == 1: item = items[0] def g(obj): return obj[item] else: def g(obj): return tuple(obj[item] for item in items) return g The items can be any type accepted by the operand’s __getitem__() method. Dictionaries accept any hashable value. Lists, tuples, and strings accept an index or a slice: >>> itemgetter(1)('ABCDEFG') 'B' >>> itemgetter(1, 3, 5)('ABCDEFG') ('B', 'D', 'F') >>> itemgetter(slice(2, None))('ABCDEFG') 'CDEFG' >>> soldier = dict(rank='captain', name='dotterbart') >>> itemgetter('rank')(soldier) 'captain' Example of using itemgetter() to retrieve specific fields from a tuple record: >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)] >>> getcount = itemgetter(1) >>> list(map(getcount, inventory)) [3, 2, 5, 1] >>> sorted(inventory, key=getcount) [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
python.library.operator#operator.itemgetter
operator.itruediv(a, b) operator.__itruediv__(a, b) a = itruediv(a, b) is equivalent to a /= b.
python.library.operator#operator.itruediv
operator.ixor(a, b) operator.__ixor__(a, b) a = ixor(a, b) is equivalent to a ^= b.
python.library.operator#operator.ixor
operator.lt(a, b) operator.le(a, b) operator.eq(a, b) operator.ne(a, b) operator.ge(a, b) operator.gt(a, b) operator.__lt__(a, b) operator.__le__(a, b) operator.__eq__(a, b) operator.__ne__(a, b) operator.__ge__(a, b) operator.__gt__(a, b) Perform “rich comparisons” between a and b. Specifically, lt(a, b) is equivalent to a < b, le(a, b) is equivalent to a <= b, eq(a, b) is equivalent to a == b, ne(a, b) is equivalent to a != b, gt(a, b) is equivalent to a > b and ge(a, b) is equivalent to a >= b. Note that these functions can return any value, which may or may not be interpretable as a Boolean value. See Comparisons for more information about rich comparisons.
python.library.operator#operator.le
operator.length_hint(obj, default=0) Return an estimated length for the object o. First try to return its actual length, then an estimate using object.__length_hint__(), and finally return the default value. New in version 3.4.
python.library.operator#operator.length_hint