Base class for binary streams that support some kind of buffering. It inherits IOBase. There is no public constructor.
The main difference with RawIOBase is that methods read(), readinto() and write() will try (respectively) to read as much input as requested or to consume all given output, at the expense of making perhaps more than one system call.
In addition, those methods can raise BlockingIOError if the underlying raw stream is in non-blocking mode and cannot take or give enough data; unlike their RawIOBase counterparts, they will never return None.
Besides, the read() method does not have a default implementation that defers to readinto().
A typical BufferedIOBase implementation should not inherit from a RawIOBase implementation, but wrap one, like BufferedWriter and BufferedReader do.
BufferedIOBase provides or overrides these data attributes and methods in addition to those from IOBase:
The underlying raw stream (a RawIOBase instance) that BufferedIOBase deals with. This is not part of the BufferedIOBase API and may not exist on some implementations.
Separate the underlying raw stream from the buffer and return it.
After the raw stream has been detached, the buffer is in an unusable state.
Some buffers, like BytesIO, do not have the concept of a single raw stream to return from this method. They raise UnsupportedOperation.
New in version 3.1.
Read and return up to size bytes. If the argument is omitted, None, or negative, data is read and returned until EOF is reached. An empty bytes object is returned if the stream is already at EOF.
If the argument is positive, and the underlying raw stream is not interactive, multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first). But for interactive raw streams, at most one raw read will be issued, and a short result does not imply that EOF is imminent.
A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.
Read and return up to size bytes, with at most one call to the underlying raw stream’s read() (or readinto()) method. This can be useful if you are implementing your own buffering on top of a BufferedIOBase object.
If size is -1 (the default), an arbitrary number of bytes are returned (more than zero unless EOF is reached).
Read bytes into a pre-allocated, writable bytes-like object b and return the number of bytes read. For example, b might be a bytearray.
Like read(), multiple reads may be issued to the underlying raw stream, unless the latter is interactive.
A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.
Read bytes into a pre-allocated, writable bytes-like object b, using at most one call to the underlying raw stream’s read() (or readinto()) method. Return the number of bytes read.
A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.
New in version 3.5.
Write the given bytes-like object, b, and return the number of bytes written (always equal to the length of b in bytes, since if the write fails an OSError will be raised). Depending on the actual implementation, these bytes may be readily written to the underlying stream, or held in a buffer for performance and latency reasons.
When in non-blocking mode, a BlockingIOError is raised if the data needed to be written to the raw stream but it couldn’t accept all the data without blocking.
The caller may release or mutate b after this method returns, so the implementation should only access b during the method call.


Separate the underlying raw stream from the buffer and return it.
After the raw stream has been detached, the buffer is in an unusable state.
Some buffers, like BytesIO, do not have the concept of a single raw stream to return from this method. They raise UnsupportedOperation.
New in version 3.1.


The underlying raw stream (a RawIOBase instance) that BufferedIOBase deals with. This is not part of the BufferedIOBase API and may not exist on some implementations.


Read and return up to size bytes. If the argument is omitted, None, or negative, data is read and returned until EOF is reached. An empty bytes object is returned if the stream is already at EOF.
If the argument is positive, and the underlying raw stream is not interactive, multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first). But for interactive raw streams, at most one raw read will be issued, and a short result does not imply that EOF is imminent.
A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.


Read and return up to size bytes, with at most one call to the underlying raw stream’s read() (or readinto()) method. This can be useful if you are implementing your own buffering on top of a BufferedIOBase object.
If size is -1 (the default), an arbitrary number of bytes are returned (more than zero unless EOF is reached).


Read bytes into a pre-allocated, writable bytes-like object b and return the number of bytes read. For example, b might be a bytearray.
Like read(), multiple reads may be issued to the underlying raw stream, unless the latter is interactive.
A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.


Read bytes into a pre-allocated, writable bytes-like object b, using at most one call to the underlying raw stream’s read() (or readinto()) method. Return the number of bytes read.
A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.
New in version 3.5.


Write the given bytes-like object, b, and return the number of bytes written (always equal to the length of b in bytes, since if the write fails an OSError will be raised). Depending on the actual implementation, these bytes may be readily written to the underlying stream, or held in a buffer for performance and latency reasons.
When in non-blocking mode, a BlockingIOError is raised if the data needed to be written to the raw stream but it couldn’t accept all the data without blocking.
The caller may release or mutate b after this method returns, so the implementation should only access b during the method call.


A buffered binary stream providing higher-level access to a seekable RawIOBase raw binary stream. It inherits BufferedReader and BufferedWriter.
The constructor creates a reader and writer for a seekable raw stream, given in the first argument. If the buffer_size is omitted it defaults to DEFAULT_BUFFER_SIZE.
BufferedRandom is capable of anything BufferedReader or BufferedWriter can do. In addition, seek() and tell() are guaranteed to be implemented.


A buffered binary stream providing higher-level access to a readable, non seekable RawIOBase raw binary stream. It inherits BufferedIOBase.
When reading data from this object, a larger amount of data may be requested from the underlying raw stream, and kept in an internal buffer. The buffered data can then be returned directly on subsequent reads.
The constructor creates a BufferedReader for the given readable raw stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE is used.
BufferedReader provides or overrides these methods in addition to those from BufferedIOBase and IOBase:
Return bytes from the stream without advancing the position. At most one single read on the raw stream is done to satisfy the call. The number of bytes returned may be less or more than requested.
Read and return size bytes, or if size is not given or negative, until EOF or if the read call would block in non-blocking mode.
Read and return up to size bytes with only one call on the raw stream. If at least one byte is buffered, only buffered bytes are returned. Otherwise, one raw stream read call is made.
Changed in version 3.7: The size argument is now optional.


Return bytes from the stream without advancing the position. At most one single read on the raw stream is done to satisfy the call. The number of bytes returned may be less or more than requested.


Read and return size bytes, or if size is not given or negative, until EOF or if the read call would block in non-blocking mode.


Read and return up to size bytes with only one call on the raw stream. If at least one byte is buffered, only buffered bytes are returned. Otherwise, one raw stream read call is made.
Changed in version 3.7: The size argument is now optional.


A buffered binary stream providing higher-level access to two non seekable RawIOBase raw binary streams—one readable, the other writeable. It inherits BufferedIOBase.
reader and writer are RawIOBase objects that are readable and writeable respectively. If the buffer_size is omitted it defaults to DEFAULT_BUFFER_SIZE.
BufferedRWPair implements all of BufferedIOBase’s methods except for detach(), which raises UnsupportedOperation.
Warning
BufferedRWPair does not attempt to synchronize accesses to its underlying raw streams. You should not pass it the same object as reader and writer; use BufferedRandom instead.


A buffered binary stream providing higher-level access to a writeable, non seekable RawIOBase raw binary stream. It inherits BufferedIOBase.
When writing to this object, data is normally placed into an internal buffer. The buffer will be written out to the underlying RawIOBase object under various conditions, including:
The constructor creates a BufferedWriter for the given writeable raw stream. If the buffer_size is not given, it defaults to DEFAULT_BUFFER_SIZE.
BufferedWriter provides or overrides these methods in addition to those from BufferedIOBase and IOBase:
Force bytes held in the buffer into the raw stream. A BlockingIOError should be raised if the raw stream blocks.
Write the bytes-like object, b, and return the number of bytes written. When in non-blocking mode, a BlockingIOError is raised if the buffer needs to be written out but the raw stream blocks.


Force bytes held in the buffer into the raw stream. A BlockingIOError should be raised if the raw stream blocks.


Write the bytes-like object, b, and return the number of bytes written. When in non-blocking mode, a BlockingIOError is raised if the buffer needs to be written out but the raw stream blocks.


A binary stream using an in-memory bytes buffer. It inherits BufferedIOBase. The buffer is discarded when the close() method is called.
The optional argument initial_bytes is a bytes-like object that contains initial data.
BytesIO provides or overrides these methods in addition to those from BufferedIOBase and IOBase:
Return a readable and writable view over the contents of the buffer without copying them. Also, mutating the view will transparently update the contents of the buffer:
Note
As long as the view exists, the BytesIO object cannot be resized or closed.
New in version 3.2.
Return bytes containing the entire contents of the buffer.
In BytesIO, this is the same as read().
Changed in version 3.7: The size argument is now optional.
In BytesIO, this is the same as readinto().
New in version 3.5.


Return a readable and writable view over the contents of the buffer without copying them. Also, mutating the view will transparently update the contents of the buffer:
Note
As long as the view exists, the BytesIO object cannot be resized or closed.
New in version 3.2.


Return bytes containing the entire contents of the buffer.


In BytesIO, this is the same as read().
Changed in version 3.7: The size argument is now optional.


In BytesIO, this is the same as readinto().
New in version 3.5.


An int containing the default buffer size used by the module’s buffered I/O classes. open() uses the file’s blksize (as obtained by os.stat()) if possible.


A raw binary stream representing an OS-level file containing bytes data. It inherits RawIOBase.
The name can be one of two things:
The mode can be 'r', 'w', 'x' or 'a' for reading (default), writing, exclusive creation or appending. The file will be created if it doesn’t exist when opened for writing or appending; it will be truncated when opened for writing. FileExistsError will be raised if it already exists when opened for creating. Opening a file for creating implies writing, so this mode behaves in a similar way to 'w'. Add a '+' to the mode to allow simultaneous reading and writing.
The read() (when called with a positive argument), readinto() and write() methods on this class will only make one system call.
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 (name, 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.
See the open() built-in function for examples on using the opener parameter.
Changed in version 3.3: The opener parameter was added. The 'x' mode was added.
Changed in version 3.4: The file is now non-inheritable.
FileIO provides these data attributes in addition to those from RawIOBase and IOBase:
The mode as given in the constructor.
The file name. This is the file descriptor of the file when no name is given in the constructor.


The file name. This is the file descriptor of the file when no name is given in the constructor.


A helper codec that decodes newlines for universal newlines mode. It inherits codecs.IncrementalDecoder.


The abstract base class for all I/O classes, acting on streams of bytes. There is no public constructor.
This class provides empty abstract implementations for many methods that derived classes can override selectively; the default implementations represent a file that cannot be read, written or seeked.
Even though IOBase does not declare read() or write() because their signatures will vary, implementations and clients should consider those methods part of the interface. Also, implementations may raise a ValueError (or UnsupportedOperation) when operations they do not support are called.
The basic type used for binary data read from or written to a file is bytes. Other bytes-like objects are accepted as method arguments too. Text I/O classes work with str data.
Note that calling any method (even inquiries) on a closed stream is undefined. Implementations may raise ValueError in this case.
IOBase (and its subclasses) supports the iterator protocol, meaning that an IOBase object can be iterated over yielding the lines in a stream. Lines are defined slightly differently depending on whether the stream is a binary stream (yielding bytes), or a text stream (yielding character strings). See readline() below.
IOBase is also a context manager and therefore supports the with statement. In this example, file is closed after the with statement’s suite is finished—even if an exception occurs:
IOBase provides these data attributes and methods:
Flush and close this stream. This method has no effect if the file is already closed. Once the file is closed, any operation on the file (e.g. reading or writing) will raise a ValueError.
As a convenience, it is allowed to call this method more than once; only the first call, however, will have an effect.
True if the stream is closed.
Return the underlying file descriptor (an integer) of the stream if it exists. An OSError is raised if the IO object does not use a file descriptor.
Flush the write buffers of the stream if applicable. This does nothing for read-only and non-blocking streams.
Return True if the stream is interactive (i.e., connected to a terminal/tty device).
Return True if the stream can be read from. If False, read() will raise OSError.
Read and return one line from the stream. If size is specified, at most size bytes will be read.
The line terminator is always b'\n' for binary files; for text files, the newline argument to open() can be used to select the line terminator(s) recognized.
Read and return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.
Note that it’s already possible to iterate on file objects using for
line in file: ... without calling file.readlines().
Change the stream position to the given byte offset. offset is interpreted relative to the position indicated by whence. The default value for whence is SEEK_SET. Values for whence are:
Return the new absolute position.
New in version 3.1: The SEEK_* constants.
New in version 3.3: Some operating systems could support additional values, like os.SEEK_HOLE or os.SEEK_DATA. The valid values for a file could depend on it being open in text or binary mode.
Return True if the stream supports random access. If False, seek(), tell() and truncate() will raise OSError.
Return the current stream position.
Resize the stream to the given size in bytes (or the current position if size is not specified). The current stream position isn’t changed. This resizing can extend or reduce the current file size. In case of extension, the contents of the new file area depend on the platform (on most systems, additional bytes are zero-filled). The new file size is returned.
Changed in version 3.5: Windows will now zero-fill files when extending.
Return True if the stream supports writing. If False, write() and truncate() will raise OSError.
Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.
Prepare for object destruction. IOBase provides a default implementation of this method that calls the instance’s close() method.


Flush and close this stream. This method has no effect if the file is already closed. Once the file is closed, any operation on the file (e.g. reading or writing) will raise a ValueError.
As a convenience, it is allowed to call this method more than once; only the first call, however, will have an effect.


Return the underlying file descriptor (an integer) of the stream if it exists. An OSError is raised if the IO object does not use a file descriptor.


Flush the write buffers of the stream if applicable. This does nothing for read-only and non-blocking streams.


Return True if the stream is interactive (i.e., connected to a terminal/tty device).


Return True if the stream can be read from. If False, read() will raise OSError.


Read and return one line from the stream. If size is specified, at most size bytes will be read.
The line terminator is always b'\n' for binary files; for text files, the newline argument to open() can be used to select the line terminator(s) recognized.


Read and return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.
Note that it’s already possible to iterate on file objects using for
line in file: ... without calling file.readlines().


Change the stream position to the given byte offset. offset is interpreted relative to the position indicated by whence. The default value for whence is SEEK_SET. Values for whence are:
Return the new absolute position.
New in version 3.1: The SEEK_* constants.
New in version 3.3: Some operating systems could support additional values, like os.SEEK_HOLE or os.SEEK_DATA. The valid values for a file could depend on it being open in text or binary mode.


Return True if the stream supports random access. If False, seek(), tell() and truncate() will raise OSError.


Resize the stream to the given size in bytes (or the current position if size is not specified). The current stream position isn’t changed. This resizing can extend or reduce the current file size. In case of extension, the contents of the new file area depend on the platform (on most systems, additional bytes are zero-filled). The new file size is returned.
Changed in version 3.5: Windows will now zero-fill files when extending.


Return True if the stream supports writing. If False, write() and truncate() will raise OSError.


Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.


Prepare for object destruction. IOBase provides a default implementation of this method that calls the instance’s close() method.


This is an alias for the builtin open() function.
This function raises an auditing event open with arguments path, mode and flags. The mode and flags arguments may have been modified or inferred from the original call.


Opens the provided file with mode 'rb'. This function should be used when the intent is to treat the contents as executable code.
path should be a str and an absolute path.
The behavior of this function may be overridden by an earlier call to the PyFile_SetOpenCodeHook(). However, assuming that path is a str and an absolute path, open_code(path) should always behave the same as open(path, 'rb'). Overriding the behavior is intended for additional validation or preprocessing of the file.
New in version 3.8.


Base class for raw binary streams. It inherits IOBase. There is no public constructor.
Raw binary streams typically provide low-level access to an underlying OS device or API, and do not try to encapsulate it in high-level primitives (this functionality is done at a higher-level in buffered binary streams and text streams, described later in this page).
RawIOBase provides these methods in addition to those from IOBase:
Read up to size bytes from the object and return them. As a convenience, if size is unspecified or -1, all bytes until EOF are returned. Otherwise, only one system call is ever made. Fewer than size bytes may be returned if the operating system call returns fewer than size bytes.
If 0 bytes are returned, and size was not 0, this indicates end of file. If the object is in non-blocking mode and no bytes are available, None is returned.
The default implementation defers to readall() and readinto().
Read and return all the bytes from the stream until EOF, using multiple calls to the stream if necessary.
Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. For example, b might be a bytearray. If the object is in non-blocking mode and no bytes are available, None is returned.
Write the given bytes-like object, b, to the underlying raw stream, and return the number of bytes written. This can be less than the length of b in bytes, depending on specifics of the underlying raw stream, and especially if it is in non-blocking mode. None is returned if the raw stream is set not to block and no single byte could be readily written to it. The caller may release or mutate b after this method returns, so the implementation should only access b during the method call.


Read up to size bytes from the object and return them. As a convenience, if size is unspecified or -1, all bytes until EOF are returned. Otherwise, only one system call is ever made. Fewer than size bytes may be returned if the operating system call returns fewer than size bytes.
If 0 bytes are returned, and size was not 0, this indicates end of file. If the object is in non-blocking mode and no bytes are available, None is returned.
The default implementation defers to readall() and readinto().


Read and return all the bytes from the stream until EOF, using multiple calls to the stream if necessary.


Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. For example, b might be a bytearray. If the object is in non-blocking mode and no bytes are available, None is returned.


Write the given bytes-like object, b, to the underlying raw stream, and return the number of bytes written. This can be less than the length of b in bytes, depending on specifics of the underlying raw stream, and especially if it is in non-blocking mode. None is returned if the raw stream is set not to block and no single byte could be readily written to it. The caller may release or mutate b after this method returns, so the implementation should only access b during the method call.


A text stream using an in-memory text buffer. It inherits TextIOBase.
The text buffer is discarded when the close() method is called.
The initial value of the buffer can be set by providing initial_value. If newline translation is enabled, newlines will be encoded as if by write(). The stream is positioned at the start of the buffer.
The newline argument works like that of TextIOWrapper, except that when writing output to the stream, if newline is None, newlines are written as \n on all platforms.
StringIO provides this method in addition to those from TextIOBase and IOBase:
Return a str containing the entire contents of the buffer. Newlines are decoded as if by read(), although the stream position is not changed.
Example usage:


Return a str containing the entire contents of the buffer. Newlines are decoded as if by read(), although the stream position is not changed.


Base class for text streams. This class provides a character and line based interface to stream I/O. It inherits IOBase. There is no public constructor.
TextIOBase provides or overrides these data attributes and methods in addition to those from IOBase:
The name of the encoding used to decode the stream’s bytes into strings, and to encode strings into bytes.
The error setting of the decoder or encoder.
A string, a tuple of strings, or None, indicating the newlines translated so far. Depending on the implementation and the initial constructor flags, this may not be available.
The underlying binary buffer (a BufferedIOBase instance) that TextIOBase deals with. This is not part of the TextIOBase API and may not exist in some implementations.
Separate the underlying binary buffer from the TextIOBase and return it.
After the underlying buffer has been detached, the TextIOBase is in an unusable state.
Some TextIOBase implementations, like StringIO, may not have the concept of an underlying buffer and calling this method will raise UnsupportedOperation.
New in version 3.1.
Read and return at most size characters from the stream as a single str. If size is negative or None, reads until EOF.
Read until newline or EOF and return a single str. If the stream is already at EOF, an empty string is returned.
If size is specified, at most size characters will be read.
Change the stream position to the given offset. Behaviour depends on the whence parameter. The default value for whence is SEEK_SET.
Return the new absolute position as an opaque number.
New in version 3.1: The SEEK_* constants.
Return the current stream position as an opaque number. The number does not usually represent a number of bytes in the underlying binary storage.
Write the string s to the stream and return the number of characters written.


The underlying binary buffer (a BufferedIOBase instance) that TextIOBase deals with. This is not part of the TextIOBase API and may not exist in some implementations.


Separate the underlying binary buffer from the TextIOBase and return it.
After the underlying buffer has been detached, the TextIOBase is in an unusable state.
Some TextIOBase implementations, like StringIO, may not have the concept of an underlying buffer and calling this method will raise UnsupportedOperation.
New in version 3.1.


The name of the encoding used to decode the stream’s bytes into strings, and to encode strings into bytes.


The error setting of the decoder or encoder.


A string, a tuple of strings, or None, indicating the newlines translated so far. Depending on the implementation and the initial constructor flags, this may not be available.


Read and return at most size characters from the stream as a single str. If size is negative or None, reads until EOF.


Read until newline or EOF and return a single str. If the stream is already at EOF, an empty string is returned.
If size is specified, at most size characters will be read.


Change the stream position to the given offset. Behaviour depends on the whence parameter. The default value for whence is SEEK_SET.
Return the new absolute position as an opaque number.
New in version 3.1: The SEEK_* constants.


Return the current stream position as an opaque number. The number does not usually represent a number of bytes in the underlying binary storage.


Write the string s to the stream and return the number of characters written.


A buffered text stream providing higher-level access to a BufferedIOBase buffered binary stream. It inherits TextIOBase.
encoding gives the name of the encoding that the stream will be decoded or encoded with. It defaults to locale.getpreferredencoding(False).
errors is an optional string that specifies how encoding and decoding errors are to be handled. Pass 'strict' to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ignore 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. 'backslashreplace' causes malformed data to be replaced by a backslashed escape sequence. When writing, 'xmlcharrefreplace' (replace with the appropriate XML character reference) or 'namereplace' (replace with \N{...} escape sequences) can be used. Any other error handling name that has been registered with codecs.register_error() is also valid.
newline controls how line endings are handled. It can be None, '', '\n', '\r', and '\r\n'. It works as follows:
If line_buffering is True, flush() is implied when a call to write contains a newline character or a carriage return.
If write_through is True, calls to write() are guaranteed not to be buffered: any data written on the TextIOWrapper object is immediately handled to its underlying binary buffer.
Changed in version 3.3: The write_through argument has been added.
Changed in version 3.3: The default encoding is now locale.getpreferredencoding(False) instead of locale.getpreferredencoding(). Don’t change temporary the locale encoding using locale.setlocale(), use the current locale encoding instead of the user preferred encoding.
TextIOWrapper provides these data attributes and methods in addition to those from TextIOBase and IOBase:
Whether line buffering is enabled.
Whether writes are passed immediately to the underlying binary buffer.
New in version 3.7.
Reconfigure this text stream using new settings for encoding, errors, newline, line_buffering and write_through.
Parameters not specified keep current settings, except errors='strict' is used when encoding is specified but errors is not specified.
It is not possible to change the encoding or newline if some data has already been read from the stream. On the other hand, changing encoding after write is possible.
This method does an implicit stream flush before setting the new parameters.
New in version 3.7.


Reconfigure this text stream using new settings for encoding, errors, newline, line_buffering and write_through.
Parameters not specified keep current settings, except errors='strict' is used when encoding is specified but errors is not specified.
It is not possible to change the encoding or newline if some data has already been read from the stream. On the other hand, changing encoding after write is possible.
This method does an implicit stream flush before setting the new parameters.
New in version 3.7.


Whether writes are passed immediately to the underlying binary buffer.
New in version 3.7.


An exception inheriting OSError and ValueError that is raised when an unsupported operation is called on a stream.


Source code: Lib/ipaddress.py
ipaddress provides the capabilities to create, manipulate and operate on IPv4 and IPv6 addresses and networks.
The functions and classes in this module make it straightforward to handle various tasks related to IP addresses, including checking whether or not two hosts are on the same subnet, iterating over all hosts in a particular subnet, checking whether or not a string represents a valid IP address or network definition, and so on.
This is the full module API reference—for an overview and introduction, see An introduction to the ipaddress module.
New in version 3.3.
The ipaddress module provides factory functions to conveniently create IP addresses, networks and interfaces:
Return an IPv4Address or IPv6Address object depending on the IP address passed as argument. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. A ValueError is raised if address does not represent a valid IPv4 or IPv6 address.
Return an IPv4Network or IPv6Network object depending on the IP address passed as argument. address is a string or integer representing the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. strict is passed to IPv4Network or IPv6Network constructor. A ValueError is raised if address does not represent a valid IPv4 or IPv6 address, or if the network has host bits set.
Return an IPv4Interface or IPv6Interface object depending on the IP address passed as argument. address is a string or integer representing the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. A ValueError is raised if address does not represent a valid IPv4 or IPv6 address.
One downside of these convenience functions is that the need to handle both IPv4 and IPv6 formats means that error messages provide minimal information on the precise error, as the functions don’t know whether the IPv4 or IPv6 format was intended. More detailed error reporting can be obtained by calling the appropriate version specific class constructors directly.
The IPv4Address and IPv6Address objects share a lot of common attributes. Some attributes that are only meaningful for IPv6 addresses are also implemented by IPv4Address objects, in order to make it easier to write code that handles both IP versions correctly. Address objects are hashable, so they can be used as keys in dictionaries.
Construct an IPv4 address. An AddressValueError is raised if address is not a valid IPv4 address.
The following constitutes a valid IPv4 address:
The appropriate version number: 4 for IPv4, 6 for IPv6.
The total number of bits in the address representation for this version: 32 for IPv4, 128 for IPv6.
The prefix defines the number of leading bits in an address that are compared to determine whether or not an address is part of a network.
The string representation in dotted decimal notation. Leading zeroes are never included in the representation.
As IPv4 does not define a shorthand notation for addresses with octets set to zero, these two attributes are always the same as str(addr) for IPv4 addresses. Exposing these attributes makes it easier to write display code that can handle both IPv4 and IPv6 addresses.
The binary representation of this address - a bytes object of the appropriate length (most significant octet first). This is 4 bytes for IPv4 and 16 bytes for IPv6.
The name of the reverse DNS PTR record for the IP address, e.g.:
This is the name that could be used for performing a PTR lookup, not the resolved hostname itself.
New in version 3.5.
True if the address is reserved for multicast use. See RFC 3171 (for IPv4) or RFC 2373 (for IPv6).
True if the address is allocated for private networks. See iana-ipv4-special-registry (for IPv4) or iana-ipv6-special-registry (for IPv6).
True if the address is allocated for public networks. See iana-ipv4-special-registry (for IPv4) or iana-ipv6-special-registry (for IPv6).
New in version 3.4.
True if the address is unspecified. See RFC 5735 (for IPv4) or RFC 2373 (for IPv6).
True if the address is otherwise IETF reserved.
True if this is a loopback address. See RFC 3330 (for IPv4) or RFC 2373 (for IPv6).
True if the address is reserved for link-local usage. See RFC 3927.
Returns a string representation of the IP address, controlled by an explicit format string. fmt can be one of the following: 's', the default option, equivalent to str(), 'b' for a zero-padded binary string, 'X' or 'x' for an uppercase or lowercase hexadecimal representation, or 'n', which is equivalent to 'b' for IPv4 addresses and 'x' for IPv6. For binary and hexadecimal representations, the form specifier '#' and the grouping option '_' are available. __format__ is used by format, str.format and f-strings.
New in version 3.9.
Construct an IPv6 address. An AddressValueError is raised if address is not a valid IPv6 address.
The following constitutes a valid IPv6 address:
A string consisting of eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons. This describes an exploded (longhand) notation. The string can also be compressed (shorthand notation) by various means. See RFC 4291 for details. For example, "0000:0000:0000:0000:0000:0abc:0007:0def" can be compressed to "::abc:7:def".
Optionally, the string may also have a scope zone ID, expressed with a suffix %scope_id. If present, the scope ID must be non-empty, and may not contain %. See RFC 4007 for details. For example, fe80::1234%1 might identify address fe80::1234 on the first link of the node.
The short form of the address representation, with leading zeroes in groups omitted and the longest sequence of groups consisting entirely of zeroes collapsed to a single empty group.
This is also the value returned by str(addr) for IPv6 addresses.
The long form of the address representation, with all leading zeroes and groups consisting entirely of zeroes included.
For the following attributes and methods, see the corresponding documentation of the IPv4Address class:
New in version 3.4: is_global
True if the address is reserved for site-local usage. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193.
For addresses that appear to be IPv4 mapped addresses (starting with ::FFFF/96), this property will report the embedded IPv4 address. For any other address, this property will be None.
For scoped addresses as defined by RFC 4007, this property identifies the particular zone of the address’s scope that the address belongs to, as a string. When no scope zone is specified, this property will be None.
For addresses that appear to be 6to4 addresses (starting with 2002::/16) as defined by RFC 3056, this property will report the embedded IPv4 address. For any other address, this property will be None.
For addresses that appear to be Teredo addresses (starting with 2001::/32) as defined by RFC 4380, this property will report the embedded (server, client) IP address pair. For any other address, this property will be None.
Refer to the corresponding method documentation in IPv4Address.
New in version 3.9.
To interoperate with networking interfaces such as the socket module, addresses must be converted to strings or integers. This is handled using the str() and int() builtin functions:
Note that IPv6 scoped addresses are converted to integers without scope zone ID.
Address objects support some operators. Unless stated otherwise, operators can only be applied between compatible objects (i.e. IPv4 with IPv4, IPv6 with IPv6).
Address objects can be compared with the usual set of comparison operators. Same IPv6 addresses with different scope zone IDs are not equal. Some examples:
Integers can be added to or subtracted from address objects. Some examples:
The IPv4Network and IPv6Network objects provide a mechanism for defining and inspecting IP network definitions. A network definition consists of a mask and a network address, and as such defines a range of IP addresses that equal the network address when masked (binary AND) with the mask. For example, a network definition with the mask 255.255.255.0 and the network address 192.168.1.0 consists of IP addresses in the inclusive range 192.168.1.0 to 192.168.1.255.
There are several equivalent ways to specify IP network masks. A prefix /<nbits> is a notation that denotes how many high-order bits are set in the network mask. A net mask is an IP address with some number of high-order bits set. Thus the prefix /24 is equivalent to the net mask 255.255.255.0 in IPv4, or ffff:ff00:: in IPv6. In addition, a host mask is the logical inverse of a net mask, and is sometimes used (for example in Cisco access control lists) to denote a network mask. The host mask equivalent to /24 in IPv4 is 0.0.0.255.
All attributes implemented by address objects are implemented by network objects as well. In addition, network objects implement additional attributes. All of these are common between IPv4Network and IPv6Network, so to avoid duplication they are only documented for IPv4Network. Network objects are hashable, so they can be used as keys in dictionaries.
Construct an IPv4 network definition. address can be one of the following:
A string consisting of an IP address and an optional mask, separated by a slash (/). The IP address is the network address, and the mask can be either a single number, which means it’s a prefix, or a string representation of an IPv4 address. If it’s the latter, the mask is interpreted as a net mask if it starts with a non-zero field, or as a host mask if it starts with a zero field, with the single exception of an all-zero mask which is treated as a net mask. If no mask is provided, it’s considered to be /32.
For example, the following address specifications are equivalent: 192.168.1.0/24, 192.168.1.0/255.255.255.0 and 192.168.1.0/0.0.0.255.
An AddressValueError is raised if address is not a valid IPv4 address. A NetmaskValueError is raised if the mask is not valid for an IPv4 address.
If strict is True and host bits are set in the supplied address, then ValueError is raised. Otherwise, the host bits are masked out to determine the appropriate network address.
Unless stated otherwise, all network methods accepting other network/address objects will raise TypeError if the argument’s IP version is incompatible to self.
Changed in version 3.5: Added the two-tuple form for the address constructor parameter.
Refer to the corresponding attribute documentation in IPv4Address.
These attributes are true for the network as a whole if they are true for both the network address and the broadcast address.
The network address for the network. The network address and the prefix length together uniquely define a network.
The broadcast address for the network. Packets sent to the broadcast address should be received by every host on the network.
The host mask, as an IPv4Address object.
The net mask, as an IPv4Address object.
A string representation of the network, with the mask in prefix notation.
with_prefixlen and compressed are always the same as str(network). exploded uses the exploded form the network address.
A string representation of the network, with the mask in net mask notation.
A string representation of the network, with the mask in host mask notation.
The total number of addresses in the network.
Length of the network prefix, in bits.
Returns an iterator over the usable hosts in the network. The usable hosts are all the IP addresses that belong to the network, except the network address itself and the network broadcast address. For networks with a mask length of 31, the network address and network broadcast address are also included in the result. Networks with a mask of 32 will return a list containing the single host address.
True if this network is partly or wholly contained in other or other is wholly contained in this network.
Computes the network definitions resulting from removing the given network from this one. Returns an iterator of network objects. Raises ValueError if network is not completely contained in this network.
The subnets that join to make the current network definition, depending on the argument values. prefixlen_diff is the amount our prefix length should be increased by. new_prefix is the desired new prefix of the subnets; it must be larger than our prefix. One and only one of prefixlen_diff and new_prefix must be set. Returns an iterator of network objects.
The supernet containing this network definition, depending on the argument values. prefixlen_diff is the amount our prefix length should be decreased by. new_prefix is the desired new prefix of the supernet; it must be smaller than our prefix. One and only one of prefixlen_diff and new_prefix must be set. Returns a single network object.
Return True if this network is a subnet of other.
New in version 3.7.
Return True if this network is a supernet of other.
New in version 3.7.
Compare this network to other. In this comparison only the network addresses are considered; host bits aren’t. Returns either -1, 0 or 1.
Deprecated since version 3.7: It uses the same ordering and comparison algorithm as “<”, “==”, and “>”
Construct an IPv6 network definition. address can be one of the following:
A string consisting of an IP address and an optional prefix length, separated by a slash (/). The IP address is the network address, and the prefix length must be a single number, the prefix. If no prefix length is provided, it’s considered to be /128.
Note that currently expanded netmasks are not supported. That means 2001:db00::0/24 is a valid argument while 2001:db00::0/ffff:ff00:: not.
An AddressValueError is raised if address is not a valid IPv6 address. A NetmaskValueError is raised if the mask is not valid for an IPv6 address.
If strict is True and host bits are set in the supplied address, then ValueError is raised. Otherwise, the host bits are masked out to determine the appropriate network address.
Changed in version 3.5: Added the two-tuple form for the address constructor parameter.
Returns an iterator over the usable hosts in the network. The usable hosts are all the IP addresses that belong to the network, except the Subnet-Router anycast address. For networks with a mask length of 127, the Subnet-Router anycast address is also included in the result. Networks with a mask of 128 will return a list containing the single host address.
Refer to the corresponding attribute documentation in IPv4Network.
These attribute is true for the network as a whole if it is true for both the network address and the broadcast address.
Network objects support some operators. Unless stated otherwise, operators can only be applied between compatible objects (i.e. IPv4 with IPv4, IPv6 with IPv6).
Network objects can be compared with the usual set of logical operators. Network objects are ordered first by network address, then by net mask.
Network objects can be iterated to list all the addresses belonging to the network. For iteration, all hosts are returned, including unusable hosts (for usable hosts, use the hosts() method). An example:
Network objects can act as containers of addresses. Some examples:
Interface objects are hashable, so they can be used as keys in dictionaries.
Construct an IPv4 interface. The meaning of address is as in the constructor of IPv4Network, except that arbitrary host addresses are always accepted.
IPv4Interface is a subclass of IPv4Address, so it inherits all the attributes from that class. In addition, the following attributes are available:
The address (IPv4Address) without network information.
The network (IPv4Network) this interface belongs to.
A string representation of the interface with the mask in prefix notation.
A string representation of the interface with the network as a net mask.
A string representation of the interface with the network as a host mask.
Construct an IPv6 interface. The meaning of address is as in the constructor of IPv6Network, except that arbitrary host addresses are always accepted.
IPv6Interface is a subclass of IPv6Address, so it inherits all the attributes from that class. In addition, the following attributes are available:
Refer to the corresponding attribute documentation in IPv4Interface.
Interface objects support some operators. Unless stated otherwise, operators can only be applied between compatible objects (i.e. IPv4 with IPv4, IPv6 with IPv6).
Interface objects can be compared with the usual set of logical operators.
For equality comparison (== and !=), both the IP address and network must be the same for the objects to be equal. An interface will not compare equal to any address or network object.
For ordering (<, >, etc) the rules are different. Interface and address objects with the same IP version can be compared, and the address objects will always sort before the interface objects. Two interface objects are first compared by their networks and, if those are the same, then by their IP addresses.
The module also provides the following module level functions:
Represent an address as 4 packed bytes in network (big-endian) order. address is an integer representation of an IPv4 IP address. A ValueError is raised if the integer is negative or too large to be an IPv4 IP address.
Represent an address as 16 packed bytes in network (big-endian) order. address is an integer representation of an IPv6 IP address. A ValueError is raised if the integer is negative or too large to be an IPv6 IP address.
Return an iterator of the summarized network range given the first and last IP addresses. first is the first IPv4Address or IPv6Address in the range and last is the last IPv4Address or IPv6Address in the range. A TypeError is raised if first or last are not IP addresses or are not of the same version. A ValueError is raised if last is not greater than first or if first address version is not 4 or 6.
Return an iterator of the collapsed IPv4Network or IPv6Network objects. addresses is an iterator of IPv4Network or IPv6Network objects. A TypeError is raised if addresses contains mixed version objects.
Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they’re fundamentally different, so the expression:
doesn’t make sense. There are some times however, where you may wish to have ipaddress sort these anyway. If you need to do this, you can use this function as the key argument to sorted().
obj is either a network or address object.
To support more specific error reporting from class constructors, the module defines the following exceptions:
Any value error related to the address.
Any value error related to the net mask.


Return an iterator of the collapsed IPv4Network or IPv6Network objects. addresses is an iterator of IPv4Network or IPv6Network objects. A TypeError is raised if addresses contains mixed version objects.


Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they’re fundamentally different, so the expression:
doesn’t make sense. There are some times however, where you may wish to have ipaddress sort these anyway. If you need to do this, you can use this function as the key argument to sorted().
obj is either a network or address object.


Construct an IPv4 address. An AddressValueError is raised if address is not a valid IPv4 address.
The following constitutes a valid IPv4 address:
The appropriate version number: 4 for IPv4, 6 for IPv6.
The total number of bits in the address representation for this version: 32 for IPv4, 128 for IPv6.
The prefix defines the number of leading bits in an address that are compared to determine whether or not an address is part of a network.
The string representation in dotted decimal notation. Leading zeroes are never included in the representation.
As IPv4 does not define a shorthand notation for addresses with octets set to zero, these two attributes are always the same as str(addr) for IPv4 addresses. Exposing these attributes makes it easier to write display code that can handle both IPv4 and IPv6 addresses.
The binary representation of this address - a bytes object of the appropriate length (most significant octet first). This is 4 bytes for IPv4 and 16 bytes for IPv6.
The name of the reverse DNS PTR record for the IP address, e.g.:
This is the name that could be used for performing a PTR lookup, not the resolved hostname itself.
New in version 3.5.
True if the address is reserved for multicast use. See RFC 3171 (for IPv4) or RFC 2373 (for IPv6).
True if the address is allocated for private networks. See iana-ipv4-special-registry (for IPv4) or iana-ipv6-special-registry (for IPv6).
True if the address is allocated for public networks. See iana-ipv4-special-registry (for IPv4) or iana-ipv6-special-registry (for IPv6).
New in version 3.4.
True if the address is unspecified. See RFC 5735 (for IPv4) or RFC 2373 (for IPv6).
True if the address is otherwise IETF reserved.
True if this is a loopback address. See RFC 3330 (for IPv4) or RFC 2373 (for IPv6).
True if the address is reserved for link-local usage. See RFC 3927.


The string representation in dotted decimal notation. Leading zeroes are never included in the representation.
As IPv4 does not define a shorthand notation for addresses with octets set to zero, these two attributes are always the same as str(addr) for IPv4 addresses. Exposing these attributes makes it easier to write display code that can handle both IPv4 and IPv6 addresses.


True if the address is allocated for public networks. See iana-ipv4-special-registry (for IPv4) or iana-ipv6-special-registry (for IPv6).
New in version 3.4.


True if the address is reserved for link-local usage. See RFC 3927.


True if this is a loopback address. See RFC 3330 (for IPv4) or RFC 2373 (for IPv6).


True if the address is reserved for multicast use. See RFC 3171 (for IPv4) or RFC 2373 (for IPv6).


True if the address is allocated for private networks. See iana-ipv4-special-registry (for IPv4) or iana-ipv6-special-registry (for IPv6).


True if the address is otherwise IETF reserved.


True if the address is unspecified. See RFC 5735 (for IPv4) or RFC 2373 (for IPv6).


The total number of bits in the address representation for this version: 32 for IPv4, 128 for IPv6.
The prefix defines the number of leading bits in an address that are compared to determine whether or not an address is part of a network.


The binary representation of this address - a bytes object of the appropriate length (most significant octet first). This is 4 bytes for IPv4 and 16 bytes for IPv6.


The name of the reverse DNS PTR record for the IP address, e.g.:
This is the name that could be used for performing a PTR lookup, not the resolved hostname itself.
New in version 3.5.


The appropriate version number: 4 for IPv4, 6 for IPv6.


Returns a string representation of the IP address, controlled by an explicit format string. fmt can be one of the following: 's', the default option, equivalent to str(), 'b' for a zero-padded binary string, 'X' or 'x' for an uppercase or lowercase hexadecimal representation, or 'n', which is equivalent to 'b' for IPv4 addresses and 'x' for IPv6. For binary and hexadecimal representations, the form specifier '#' and the grouping option '_' are available. __format__ is used by format, str.format and f-strings.
New in version 3.9.


Construct an IPv4 interface. The meaning of address is as in the constructor of IPv4Network, except that arbitrary host addresses are always accepted.
IPv4Interface is a subclass of IPv4Address, so it inherits all the attributes from that class. In addition, the following attributes are available:
The address (IPv4Address) without network information.
The network (IPv4Network) this interface belongs to.
A string representation of the interface with the mask in prefix notation.
A string representation of the interface with the network as a net mask.
A string representation of the interface with the network as a host mask.


The address (IPv4Address) without network information.


The network (IPv4Network) this interface belongs to.


A string representation of the interface with the network as a host mask.


A string representation of the interface with the network as a net mask.


A string representation of the interface with the mask in prefix notation.


Construct an IPv4 network definition. address can be one of the following:
A string consisting of an IP address and an optional mask, separated by a slash (/). The IP address is the network address, and the mask can be either a single number, which means it’s a prefix, or a string representation of an IPv4 address. If it’s the latter, the mask is interpreted as a net mask if it starts with a non-zero field, or as a host mask if it starts with a zero field, with the single exception of an all-zero mask which is treated as a net mask. If no mask is provided, it’s considered to be /32.
For example, the following address specifications are equivalent: 192.168.1.0/24, 192.168.1.0/255.255.255.0 and 192.168.1.0/0.0.0.255.
An AddressValueError is raised if address is not a valid IPv4 address. A NetmaskValueError is raised if the mask is not valid for an IPv4 address.
If strict is True and host bits are set in the supplied address, then ValueError is raised. Otherwise, the host bits are masked out to determine the appropriate network address.
Unless stated otherwise, all network methods accepting other network/address objects will raise TypeError if the argument’s IP version is incompatible to self.
Changed in version 3.5: Added the two-tuple form for the address constructor parameter.
Refer to the corresponding attribute documentation in IPv4Address.
These attributes are true for the network as a whole if they are true for both the network address and the broadcast address.
The network address for the network. The network address and the prefix length together uniquely define a network.
The broadcast address for the network. Packets sent to the broadcast address should be received by every host on the network.
The host mask, as an IPv4Address object.
The net mask, as an IPv4Address object.
A string representation of the network, with the mask in prefix notation.
with_prefixlen and compressed are always the same as str(network). exploded uses the exploded form the network address.
A string representation of the network, with the mask in net mask notation.
A string representation of the network, with the mask in host mask notation.
The total number of addresses in the network.
Length of the network prefix, in bits.
Returns an iterator over the usable hosts in the network. The usable hosts are all the IP addresses that belong to the network, except the network address itself and the network broadcast address. For networks with a mask length of 31, the network address and network broadcast address are also included in the result. Networks with a mask of 32 will return a list containing the single host address.
True if this network is partly or wholly contained in other or other is wholly contained in this network.
Computes the network definitions resulting from removing the given network from this one. Returns an iterator of network objects. Raises ValueError if network is not completely contained in this network.
The subnets that join to make the current network definition, depending on the argument values. prefixlen_diff is the amount our prefix length should be increased by. new_prefix is the desired new prefix of the subnets; it must be larger than our prefix. One and only one of prefixlen_diff and new_prefix must be set. Returns an iterator of network objects.
The supernet containing this network definition, depending on the argument values. prefixlen_diff is the amount our prefix length should be decreased by. new_prefix is the desired new prefix of the supernet; it must be smaller than our prefix. One and only one of prefixlen_diff and new_prefix must be set. Returns a single network object.
Return True if this network is a subnet of other.
New in version 3.7.
Return True if this network is a supernet of other.
New in version 3.7.
Compare this network to other. In this comparison only the network addresses are considered; host bits aren’t. Returns either -1, 0 or 1.
Deprecated since version 3.7: It uses the same ordering and comparison algorithm as “<”, “==”, and “>”


Computes the network definitions resulting from removing the given network from this one. Returns an iterator of network objects. Raises ValueError if network is not completely contained in this network.


The broadcast address for the network. Packets sent to the broadcast address should be received by every host on the network.


Compare this network to other. In this comparison only the network addresses are considered; host bits aren’t. Returns either -1, 0 or 1.
Deprecated since version 3.7: It uses the same ordering and comparison algorithm as “<”, “==”, and “>”


A string representation of the network, with the mask in prefix notation.
with_prefixlen and compressed are always the same as str(network). exploded uses the exploded form the network address.


The host mask, as an IPv4Address object.


Returns an iterator over the usable hosts in the network. The usable hosts are all the IP addresses that belong to the network, except the network address itself and the network broadcast address. For networks with a mask length of 31, the network address and network broadcast address are also included in the result. Networks with a mask of 32 will return a list containing the single host address.


These attributes are true for the network as a whole if they are true for both the network address and the broadcast address.


Refer to the corresponding attribute documentation in IPv4Address.


The network address for the network. The network address and the prefix length together uniquely define a network.


The total number of addresses in the network.


True if this network is partly or wholly contained in other or other is wholly contained in this network.


The subnets that join to make the current network definition, depending on the argument values. prefixlen_diff is the amount our prefix length should be increased by. new_prefix is the desired new prefix of the subnets; it must be larger than our prefix. One and only one of prefixlen_diff and new_prefix must be set. Returns an iterator of network objects.


Return True if this network is a subnet of other.
New in version 3.7.


The supernet containing this network definition, depending on the argument values. prefixlen_diff is the amount our prefix length should be decreased by. new_prefix is the desired new prefix of the supernet; it must be smaller than our prefix. One and only one of prefixlen_diff and new_prefix must be set. Returns a single network object.


Return True if this network is a supernet of other.
New in version 3.7.


A string representation of the network, with the mask in host mask notation.


A string representation of the network, with the mask in net mask notation.


Construct an IPv6 address. An AddressValueError is raised if address is not a valid IPv6 address.
The following constitutes a valid IPv6 address:
A string consisting of eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons. This describes an exploded (longhand) notation. The string can also be compressed (shorthand notation) by various means. See RFC 4291 for details. For example, "0000:0000:0000:0000:0000:0abc:0007:0def" can be compressed to "::abc:7:def".
Optionally, the string may also have a scope zone ID, expressed with a suffix %scope_id. If present, the scope ID must be non-empty, and may not contain %. See RFC 4007 for details. For example, fe80::1234%1 might identify address fe80::1234 on the first link of the node.
The short form of the address representation, with leading zeroes in groups omitted and the longest sequence of groups consisting entirely of zeroes collapsed to a single empty group.
This is also the value returned by str(addr) for IPv6 addresses.
The long form of the address representation, with all leading zeroes and groups consisting entirely of zeroes included.
For the following attributes and methods, see the corresponding documentation of the IPv4Address class:
New in version 3.4: is_global
True if the address is reserved for site-local usage. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193.
For addresses that appear to be IPv4 mapped addresses (starting with ::FFFF/96), this property will report the embedded IPv4 address. For any other address, this property will be None.
For scoped addresses as defined by RFC 4007, this property identifies the particular zone of the address’s scope that the address belongs to, as a string. When no scope zone is specified, this property will be None.
For addresses that appear to be 6to4 addresses (starting with 2002::/16) as defined by RFC 3056, this property will report the embedded IPv4 address. For any other address, this property will be None.
For addresses that appear to be Teredo addresses (starting with 2001::/32) as defined by RFC 4380, this property will report the embedded (server, client) IP address pair. For any other address, this property will be None.


For addresses that appear to be IPv4 mapped addresses (starting with ::FFFF/96), this property will report the embedded IPv4 address. For any other address, this property will be None.


True if the address is reserved for site-local usage. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193.


For scoped addresses as defined by RFC 4007, this property identifies the particular zone of the address’s scope that the address belongs to, as a string. When no scope zone is specified, this property will be None.


For addresses that appear to be 6to4 addresses (starting with 2002::/16) as defined by RFC 3056, this property will report the embedded IPv4 address. For any other address, this property will be None.


For addresses that appear to be Teredo addresses (starting with 2001::/32) as defined by RFC 4380, this property will report the embedded (server, client) IP address pair. For any other address, this property will be None.


Refer to the corresponding method documentation in IPv4Address.
New in version 3.9.


Construct an IPv6 interface. The meaning of address is as in the constructor of IPv6Network, except that arbitrary host addresses are always accepted.
IPv6Interface is a subclass of IPv6Address, so it inherits all the attributes from that class. In addition, the following attributes are available:
Refer to the corresponding attribute documentation in IPv4Interface.


Refer to the corresponding attribute documentation in IPv4Interface.


Construct an IPv6 network definition. address can be one of the following:
A string consisting of an IP address and an optional prefix length, separated by a slash (/). The IP address is the network address, and the prefix length must be a single number, the prefix. If no prefix length is provided, it’s considered to be /128.
Note that currently expanded netmasks are not supported. That means 2001:db00::0/24 is a valid argument while 2001:db00::0/ffff:ff00:: not.
An AddressValueError is raised if address is not a valid IPv6 address. A NetmaskValueError is raised if the mask is not valid for an IPv6 address.
If strict is True and host bits are set in the supplied address, then ValueError is raised. Otherwise, the host bits are masked out to determine the appropriate network address.
Changed in version 3.5: Added the two-tuple form for the address constructor parameter.
Returns an iterator over the usable hosts in the network. The usable hosts are all the IP addresses that belong to the network, except the Subnet-Router anycast address. For networks with a mask length of 127, the Subnet-Router anycast address is also included in the result. Networks with a mask of 128 will return a list containing the single host address.
Refer to the corresponding attribute documentation in IPv4Network.
These attribute is true for the network as a whole if it is true for both the network address and the broadcast address.


Refer to the corresponding attribute documentation in IPv4Network.


Returns an iterator over the usable hosts in the network. The usable hosts are all the IP addresses that belong to the network, except the Subnet-Router anycast address. For networks with a mask length of 127, the Subnet-Router anycast address is also included in the result. Networks with a mask of 128 will return a list containing the single host address.


These attribute is true for the network as a whole if it is true for both the network address and the broadcast address.


Return an IPv4Address or IPv6Address object depending on the IP address passed as argument. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. A ValueError is raised if address does not represent a valid IPv4 or IPv6 address.


Return an IPv4Interface or IPv6Interface object depending on the IP address passed as argument. address is a string or integer representing the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. A ValueError is raised if address does not represent a valid IPv4 or IPv6 address.


Return an IPv4Network or IPv6Network object depending on the IP address passed as argument. address is a string or integer representing the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. strict is passed to IPv4Network or IPv6Network constructor. A ValueError is raised if address does not represent a valid IPv4 or IPv6 address, or if the network has host bits set.


Any value error related to the net mask.


Return an iterator of the summarized network range given the first and last IP addresses. first is the first IPv4Address or IPv6Address in the range and last is the last IPv4Address or IPv6Address in the range. A TypeError is raised if first or last are not IP addresses or are not of the same version. A ValueError is raised if last is not greater than first or if first address version is not 4 or 6.


Represent an address as 4 packed bytes in network (big-endian) order. address is an integer representation of an IPv4 IP address. A ValueError is raised if the integer is negative or too large to be an IPv4 IP address.


Represent an address as 16 packed bytes in network (big-endian) order. address is an integer representation of an IPv6 IP address. A ValueError is raised if the integer is negative or too large to be an IPv6 IP address.


Raised when a file operation (such as os.remove()) is requested on a directory. Corresponds to errno EISDIR.


Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns False. If classinfo is a tuple of type objects (or recursively, other such tuples), return True if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.


Return True if class is a subclass (direct, indirect or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised.


Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iteration protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.
See also Iterator Types.
One useful application of the second form of iter() is to build a block-reader. For example, reading fixed-width blocks from a binary database file until the end of file is reached:


Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements. This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.


Return the next item from the container. If there are no further items, raise the StopIteration exception. This method corresponds to the tp_iternext slot of the type structure for Python objects in the Python/C API.


This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python.
The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python.
For instance, SML provides a tabulation tool: tabulate(f) which produces a sequence f(0), f(1), .... The same effect can be achieved in Python by combining map() and count() to form map(f, count()).
These tools and their built-in counterparts also work well with the high-speed functions in the operator module. For example, the multiplication operator can be mapped across two vectors to form an efficient dot-product: sum(map(operator.mul, vector1, vector2)).
Infinite iterators:
Iterator
Arguments
Results
Example
count()
start, [step]
start, start+step, start+2*step, …
count(10) --> 10 11 12 13 14 ...
cycle()
p
p0, p1, … plast, p0, p1, …
cycle('ABCD') --> A B C D A B C D ...
repeat()
elem [,n]
elem, elem, elem, … endlessly or up to n times
repeat(10, 3) --> 10 10 10
Iterators terminating on the shortest input sequence:
Iterator
Arguments
Results
Example
accumulate()
p [,func]
p0, p0+p1, p0+p1+p2, …
accumulate([1,2,3,4,5]) --> 1 3 6 10 15
chain()
p, q, …
p0, p1, … plast, q0, q1, …
chain('ABC', 'DEF') --> A B C D E F
chain.from_iterable()
iterable
p0, p1, … plast, q0, q1, …
chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
compress()
data, selectors
(d[0] if s[0]), (d[1] if s[1]), …
compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
dropwhile()
pred, seq
seq[n], seq[n+1], starting when pred fails
dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
filterfalse()
pred, seq
elements of seq where pred(elem) is false
filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
groupby()
iterable[, key]
sub-iterators grouped by value of key(v)
islice()
seq, [start,] stop [, step]
elements from seq[start:stop:step]
islice('ABCDEFG', 2, None) --> C D E F G
starmap()
func, seq
func(*seq[0]), func(*seq[1]), …
starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
takewhile()
pred, seq
seq[0], seq[1], until pred fails
takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
tee()
it, n
it1, it2, … itn splits one iterator into n
zip_longest()
p, q, …
(p[0], q[0]), (p[1], q[1]), …
zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
Combinatoric iterators:
Iterator
Arguments
Results
product()
p, q, … [repeat=1]
cartesian product, equivalent to a nested for-loop
permutations()
p[, r]
r-length tuples, all possible orderings, no repeated elements
combinations()
p, r
r-length tuples, in sorted order, no repeated elements
combinations_with_replacement()
p, r
r-length tuples, in sorted order, with repeated elements
Examples
Results
product('ABCD', repeat=2)
AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
permutations('ABCD', 2)
AB AC AD BA BC BD CA CB CD DA DB DC
combinations('ABCD', 2)
AB AC AD BC BD CD
combinations_with_replacement('ABCD', 2)
AA AB AC AD BB BC BD CC CD DD
The following module functions all construct and return iterators. Some provide streams of infinite length, so they should only be accessed by functions or loops that truncate the stream.
Make an iterator that returns accumulated sums, or accumulated results of other binary functions (specified via the optional func argument).
If func is supplied, it should be a function of two arguments. Elements of the input iterable may be any type that can be accepted as arguments to func. (For example, with the default operation of addition, elements may be any addable type including Decimal or Fraction.)
Usually, the number of elements output matches the input iterable. However, if the keyword argument initial is provided, the accumulation leads off with the initial value so that the output has one more element than the input iterable.
Roughly equivalent to:
There are a number of uses for the func argument. It can be set to min() for a running minimum, max() for a running maximum, or operator.mul() for a running product. Amortization tables can be built by accumulating interest and applying payments. First-order recurrence relations can be modeled by supplying the initial value in the iterable and using only the accumulated total in func argument:
See functools.reduce() for a similar function that returns only the final accumulated value.
New in version 3.2.
Changed in version 3.3: Added the optional func parameter.
Changed in version 3.8: Added the optional initial parameter.
Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Roughly equivalent to:
Alternate constructor for chain(). Gets chained inputs from a single iterable argument that is evaluated lazily. Roughly equivalent to:
Return r length subsequences of elements from the input iterable.
The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination.
Roughly equivalent to:
The code for combinations() can be also expressed as a subsequence of permutations() after filtering entries where the elements are not in sorted order (according to their position in the input pool):
The number of items returned is n! / r! / (n-r)! when 0 <= r <= n or zero when r > n.
Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.
The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on their value. So if the input elements are unique, the generated combinations will also be unique.
Roughly equivalent to:
The code for combinations_with_replacement() can be also expressed as a subsequence of product() after filtering entries where the elements are not in sorted order (according to their position in the input pool):
The number of items returned is (n+r-1)! / r! / (n-1)! when n > 0.
New in version 3.1.
Make an iterator that filters elements from data returning only those that have a corresponding element in selectors that evaluates to True. Stops when either the data or selectors iterables has been exhausted. Roughly equivalent to:
New in version 3.1.
Make an iterator that returns evenly spaced values starting with number start. Often used as an argument to map() to generate consecutive data points. Also, used with zip() to add sequence numbers. Roughly equivalent to:
When counting with floating point numbers, better accuracy can sometimes be achieved by substituting multiplicative code such as: (start + step * i
for i in count()).
Changed in version 3.1: Added step argument and allowed non-integer arguments.
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Roughly equivalent to:
Note, this member of the toolkit may require significant auxiliary storage (depending on the length of the iterable).
Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element. Note, the iterator does not produce any output until the predicate first becomes false, so it may have a lengthy start-up time. Roughly equivalent to:
Make an iterator that filters elements from iterable returning only those for which the predicate is False. If predicate is None, return the items that are false. Roughly equivalent to:
Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function.
The operation of groupby() is similar to the uniq filter in Unix. It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function). That behavior differs from SQL’s GROUP BY which aggregates common elements regardless of their input order.
The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list:
groupby() is roughly equivalent to:
Make an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped. If stop is None, then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position. Unlike regular slicing, islice() does not support negative values for start, stop, or step. Can be used to extract related fields from data where the internal structure has been flattened (for example, a multi-line report may list a name field on every third line). Roughly equivalent to:
If start is None, then iteration starts at zero. If step is None, then the step defaults to one.
Return successive r length permutations of elements in the iterable.
If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated.
The permutation tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each permutation.
Roughly equivalent to:
The code for permutations() can be also expressed as a subsequence of product(), filtered to exclude entries with repeated elements (those from the same position in the input pool):
The number of items returned is n! / (n-r)! when 0 <= r <= n or zero when r > n.
Cartesian product of input iterables.
Roughly equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).
The nested loops cycle like an odometer with the rightmost element advancing on every iteration. This pattern creates a lexicographic ordering so that if the input’s iterables are sorted, the product tuples are emitted in sorted order.
To compute the product of an iterable with itself, specify the number of repetitions with the optional repeat keyword argument. For example, product(A, repeat=4) means the same as product(A, A, A, A).
This function is roughly equivalent to the following code, except that the actual implementation does not build up intermediate results in memory:
Before product() runs, it completely consumes the input iterables, keeping pools of values in memory to generate the products. Accordingly, it is only useful with finite inputs.
Make an iterator that returns object over and over again. Runs indefinitely unless the times argument is specified. Used as argument to map() for invariant parameters to the called function. Also used with zip() to create an invariant part of a tuple record.
Roughly equivalent to:
A common use for repeat is to supply a stream of constant values to map or zip:
Make an iterator that computes the function using arguments obtained from the iterable. Used instead of map() when argument parameters are already grouped in tuples from a single iterable (the data has been “pre-zipped”). The difference between map() and starmap() parallels the distinction between function(a,b) and function(*c). Roughly equivalent to:
Make an iterator that returns elements from the iterable as long as the predicate is true. Roughly equivalent to:
Return n independent iterators from a single iterable.
The following Python code helps explain what tee does (although the actual implementation is more complex and uses only a single underlying FIFO queue).
Roughly equivalent to:
Once tee() has made a split, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed.
tee iterators are not threadsafe. A RuntimeError may be raised when using simultaneously iterators returned by the same tee() call, even if the original iterable is threadsafe.
This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().
Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted. Roughly equivalent to:
If one of the iterables is potentially infinite, then the zip_longest() function should be wrapped with something that limits the number of calls (for example islice() or takewhile()). If not specified, fillvalue defaults to None.
This section shows recipes for creating an extended toolset using the existing itertools as building blocks.
Substantially all of these recipes and many, many others can be installed from the more-itertools project found on the Python Package Index:
The extended tools offer the same high performance as the underlying toolset. The superior memory performance is kept by processing elements one at a time rather than bringing the whole iterable into memory all at once. Code volume is kept small by linking the tools together in a functional style which helps eliminate temporary variables. High speed is retained by preferring “vectorized” building blocks over the use of for-loops and generators which incur interpreter overhead.


Make an iterator that returns accumulated sums, or accumulated results of other binary functions (specified via the optional func argument).
If func is supplied, it should be a function of two arguments. Elements of the input iterable may be any type that can be accepted as arguments to func. (For example, with the default operation of addition, elements may be any addable type including Decimal or Fraction.)
Usually, the number of elements output matches the input iterable. However, if the keyword argument initial is provided, the accumulation leads off with the initial value so that the output has one more element than the input iterable.
Roughly equivalent to:
There are a number of uses for the func argument. It can be set to min() for a running minimum, max() for a running maximum, or operator.mul() for a running product. Amortization tables can be built by accumulating interest and applying payments. First-order recurrence relations can be modeled by supplying the initial value in the iterable and using only the accumulated total in func argument:
See functools.reduce() for a similar function that returns only the final accumulated value.
New in version 3.2.
Changed in version 3.3: Added the optional func parameter.
Changed in version 3.8: Added the optional initial parameter.


Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Roughly equivalent to:


Alternate constructor for chain(). Gets chained inputs from a single iterable argument that is evaluated lazily. Roughly equivalent to:


Return r length subsequences of elements from the input iterable.
The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination.
Roughly equivalent to:
The code for combinations() can be also expressed as a subsequence of permutations() after filtering entries where the elements are not in sorted order (according to their position in the input pool):
The number of items returned is n! / r! / (n-r)! when 0 <= r <= n or zero when r > n.


Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.
The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on their value. So if the input elements are unique, the generated combinations will also be unique.
Roughly equivalent to:
The code for combinations_with_replacement() can be also expressed as a subsequence of product() after filtering entries where the elements are not in sorted order (according to their position in the input pool):
The number of items returned is (n+r-1)! / r! / (n-1)! when n > 0.
New in version 3.1.


Make an iterator that filters elements from data returning only those that have a corresponding element in selectors that evaluates to True. Stops when either the data or selectors iterables has been exhausted. Roughly equivalent to:
New in version 3.1.


Make an iterator that returns evenly spaced values starting with number start. Often used as an argument to map() to generate consecutive data points. Also, used with zip() to add sequence numbers. Roughly equivalent to:
When counting with floating point numbers, better accuracy can sometimes be achieved by substituting multiplicative code such as: (start + step * i
for i in count()).
Changed in version 3.1: Added step argument and allowed non-integer arguments.


Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Roughly equivalent to:
Note, this member of the toolkit may require significant auxiliary storage (depending on the length of the iterable).


Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element. Note, the iterator does not produce any output until the predicate first becomes false, so it may have a lengthy start-up time. Roughly equivalent to:


Make an iterator that filters elements from iterable returning only those for which the predicate is False. If predicate is None, return the items that are false. Roughly equivalent to:


Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function.
The operation of groupby() is similar to the uniq filter in Unix. It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function). That behavior differs from SQL’s GROUP BY which aggregates common elements regardless of their input order.
The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list:
groupby() is roughly equivalent to:


Make an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped. If stop is None, then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position. Unlike regular slicing, islice() does not support negative values for start, stop, or step. Can be used to extract related fields from data where the internal structure has been flattened (for example, a multi-line report may list a name field on every third line). Roughly equivalent to:
If start is None, then iteration starts at zero. If step is None, then the step defaults to one.


Return successive r length permutations of elements in the iterable.
If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated.
The permutation tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each permutation.
Roughly equivalent to:
The code for permutations() can be also expressed as a subsequence of product(), filtered to exclude entries with repeated elements (those from the same position in the input pool):
The number of items returned is n! / (n-r)! when 0 <= r <= n or zero when r > n.


Cartesian product of input iterables.
Roughly equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).
The nested loops cycle like an odometer with the rightmost element advancing on every iteration. This pattern creates a lexicographic ordering so that if the input’s iterables are sorted, the product tuples are emitted in sorted order.
To compute the product of an iterable with itself, specify the number of repetitions with the optional repeat keyword argument. For example, product(A, repeat=4) means the same as product(A, A, A, A).
This function is roughly equivalent to the following code, except that the actual implementation does not build up intermediate results in memory:
Before product() runs, it completely consumes the input iterables, keeping pools of values in memory to generate the products. Accordingly, it is only useful with finite inputs.


Make an iterator that returns object over and over again. Runs indefinitely unless the times argument is specified. Used as argument to map() for invariant parameters to the called function. Also used with zip() to create an invariant part of a tuple record.
Roughly equivalent to:
A common use for repeat is to supply a stream of constant values to map or zip:


Make an iterator that computes the function using arguments obtained from the iterable. Used instead of map() when argument parameters are already grouped in tuples from a single iterable (the data has been “pre-zipped”). The difference between map() and starmap() parallels the distinction between function(a,b) and function(*c). Roughly equivalent to:


Make an iterator that returns elements from the iterable as long as the predicate is true. Roughly equivalent to:


Return n independent iterators from a single iterable.
The following Python code helps explain what tee does (although the actual implementation is more complex and uses only a single underlying FIFO queue).
Roughly equivalent to:
Once tee() has made a split, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed.
tee iterators are not threadsafe. A RuntimeError may be raised when using simultaneously iterators returned by the same tee() call, even if the original iterable is threadsafe.
This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().


Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted. Roughly equivalent to:
If one of the iterables is potentially infinite, then the zip_longest() function should be wrapped with something that limits the number of calls (for example islice() or takewhile()). If not specified, fillvalue defaults to None.