Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp (seconds since the Epoch). If the timezone item in the tuple is None, assume local time.


Parse address – which should be the value of some address-containing field such as To or Cc – into its constituent realname and email address parts. Returns a tuple of that information, unless the parse fails, in which case a 2-tuple of ('', '') is returned.


Attempts to parse a date according to the rules in RFC 2822. however, some mailers don’t follow that format as specified, so parsedate() tries to guess correctly in such cases. date is a string containing an RFC 2822 date, such as "Mon, 20 Nov 1995 19:12:08 -0500". If it succeeds in parsing the date, parsedate() returns a 9-tuple that can be passed directly to time.mktime(); otherwise None will be returned. Note that indexes 6, 7, and 8 of the result tuple are not usable.


The inverse of format_datetime(). Performs the same function as parsedate(), but on success returns a datetime. If the input date has a timezone of -0000, the datetime will be a naive datetime, and if the date is conforming to the RFCs it will represent a time in UTC but with no indication of the actual source timezone of the message the date comes from. If the input date has any other valid timezone offset, the datetime will be an aware datetime with the corresponding a timezone tzinfo.
New in version 3.3.


Performs the same function as parsedate(), but returns either None or a 10-tuple; the first 9 elements make up a tuple that can be passed directly to time.mktime(), and the tenth is the offset of the date’s timezone from UTC (which is the official term for Greenwich Mean Time) 1. If the input string has no timezone, the last element of the tuple returned is 0, which represents UTC. Note that indexes 6, 7, and 8 of the result tuple are not usable.


Return a new string with backslashes in str replaced by two backslashes, and double quotes replaced by backslash-double quote.


Return a new string which is an unquoted version of str. If str ends and begins with double quotes, they are stripped off. Likewise if str ends and begins with angle brackets, they are stripped off.


Return the nameprepped version of label. The implementation currently assumes query strings, so AllowUnassigned is true.


Convert a label to ASCII, as specified in RFC 3490. UseSTD3ASCIIRules is assumed to be false.


Convert a label to Unicode, as specified in RFC 3490.


New in version 3.4.
The ensurepip package provides support for bootstrapping the pip installer into an existing Python installation or virtual environment. This bootstrapping approach reflects the fact that pip is an independent project with its own release cycle, and the latest available stable version is bundled with maintenance and feature releases of the CPython reference interpreter.
In most cases, end users of Python shouldn’t need to invoke this module directly (as pip should be bootstrapped by default), but it may be needed if installing pip was skipped when installing Python (or when creating a virtual environment) or after explicitly uninstalling pip.
Note
This module does not access the internet. All of the components needed to bootstrap pip are included as internal parts of the package.
See also
The end user guide for installing Python packages
The original rationale and specification for this module.
The command line interface is invoked using the interpreter’s -m switch.
The simplest possible invocation is:
This invocation will install pip if it is not already installed, but otherwise does nothing. To ensure the installed version of pip is at least as recent as the one bundled with ensurepip, pass the --upgrade option:
By default, pip is installed into the current virtual environment (if one is active) or into the system site packages (if there is no active virtual environment). The installation location can be controlled through two additional command line options:
By default, the scripts pipX and pipX.Y will be installed (where X.Y stands for the version of Python used to invoke ensurepip). The scripts installed can be controlled through two additional command line options:
Providing both of the script selection options will trigger an exception.
ensurepip exposes two functions for programmatic use:
Returns a string specifying the bundled version of pip that will be installed when bootstrapping an environment.
Bootstraps pip into the current or designated environment.
root specifies an alternative root directory to install relative to. If root is None, then installation uses the default install location for the current environment.
upgrade indicates whether or not to upgrade an existing installation of an earlier version of pip to the bundled version.
user indicates whether to use the user scheme rather than installing globally.
By default, the scripts pipX and pipX.Y will be installed (where X.Y stands for the current version of Python).
If altinstall is set, then pipX will not be installed.
If default_pip is set, then pip will be installed in addition to the two regular scripts.
Setting both altinstall and default_pip will trigger ValueError.
verbosity controls the level of output to sys.stdout from the bootstrapping operation.
Raises an auditing event ensurepip.bootstrap with argument root.
Note
The bootstrapping process has side effects on both sys.path and os.environ. Invoking the command line interface in a subprocess instead allows these side effects to be avoided.
Note
The bootstrapping process may install additional modules required by pip, but other software should not assume those dependencies will always be present by default (as the dependencies may be removed in a future version of pip).


Bootstraps pip into the current or designated environment.
root specifies an alternative root directory to install relative to. If root is None, then installation uses the default install location for the current environment.
upgrade indicates whether or not to upgrade an existing installation of an earlier version of pip to the bundled version.
user indicates whether to use the user scheme rather than installing globally.
By default, the scripts pipX and pipX.Y will be installed (where X.Y stands for the current version of Python).
If altinstall is set, then pipX will not be installed.
If default_pip is set, then pip will be installed in addition to the two regular scripts.
Setting both altinstall and default_pip will trigger ValueError.
verbosity controls the level of output to sys.stdout from the bootstrapping operation.
Raises an auditing event ensurepip.bootstrap with argument root.
Note
The bootstrapping process has side effects on both sys.path and os.environ. Invoking the command line interface in a subprocess instead allows these side effects to be avoided.
Note
The bootstrapping process may install additional modules required by pip, but other software should not assume those dependencies will always be present by default (as the dependencies may be removed in a future version of pip).


Returns a string specifying the bundled version of pip that will be installed when bootstrapping an environment.


New in version 3.4.
Source code: Lib/enum.py
An enumeration is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over.
Note
Case of Enum Members
Because Enums are used to represent constants we recommend using UPPER_CASE names for enum members, and will be using that style in our examples.
This module defines four enumeration classes that can be used to define unique sets of names and values: Enum, IntEnum, Flag, and IntFlag. It also defines one decorator, unique(), and one helper, auto.
Base class for creating enumerated constants. See section Functional API for an alternate construction syntax.
Base class for creating enumerated constants that are also subclasses of int.
Base class for creating enumerated constants that can be combined using the bitwise operators without losing their IntFlag membership. IntFlag members are also subclasses of int.
Base class for creating enumerated constants that can be combined using the bitwise operations without losing their Flag membership.
Enum class decorator that ensures only one name is bound to any one value.
Instances are replaced with an appropriate value for Enum members. By default, the initial value starts at 1.
New in version 3.6: Flag, IntFlag, auto
Enumerations are created using the class syntax, which makes them easy to read and write. An alternative creation method is described in Functional API. To define an enumeration, subclass Enum as follows:
Note
Enum member values
Member values can be anything: int, str, etc.. If the exact value is unimportant you may use auto instances and an appropriate value will be chosen for you. Care must be taken if you mix auto with other values.
Note
Nomenclature
Note
Even though we use the class syntax to create Enums, Enums are not normal Python classes. See How are Enums different? for more details.
Enumeration members have human readable string representations:
…while their repr has more information:
The type of an enumeration member is the enumeration it belongs to:
Enum members also have a property that contains just their item name:
Enumerations support iteration, in definition order:
Enumeration members are hashable, so they can be used in dictionaries and sets:
Sometimes it’s useful to access members in enumerations programmatically (i.e. situations where Color.RED won’t do because the exact color is not known at program-writing time). Enum allows such access:
If you want to access enum members by name, use item access:
If you have an enum member and need its name or value:
Having two enum members with the same name is invalid:
However, two enum members are allowed to have the same value. Given two members A and B with the same value (and A defined first), B is an alias to A. By-value lookup of the value of A and B will return A. By-name lookup of B will also return A:
Note
Attempting to create a member with the same name as an already defined attribute (another member, a method, etc.) or attempting to create an attribute with the same name as a member is not allowed.
By default, enumerations allow multiple names as aliases for the same value. When this behavior isn’t desired, the following decorator can be used to ensure each value is used only once in the enumeration:
A class decorator specifically for enumerations. It searches an enumeration’s __members__ gathering any aliases it finds; if any are found ValueError is raised with the details:
If the exact value is unimportant you can use auto:
The values are chosen by _generate_next_value_(), which can be overridden:
Note
The goal of the default _generate_next_value_() method is to provide the next int in sequence with the last int provided, but the way it does this is an implementation detail and may change.
Note
The _generate_next_value_() method must be defined before any members.
Iterating over the members of an enum does not provide the aliases:
The special attribute __members__ is a read-only ordered mapping of names to members. It includes all names defined in the enumeration, including the aliases:
The __members__ attribute can be used for detailed programmatic access to the enumeration members. For example, finding all the aliases:
Enumeration members are compared by identity:
Ordered comparisons between enumeration values are not supported. Enum members are not integers (but see IntEnum below):
Equality comparisons are defined though:
Comparisons against non-enumeration values will always compare not equal (again, IntEnum was explicitly designed to behave differently, see below):
The examples above use integers for enumeration values. Using integers is short and handy (and provided by default by the Functional API), but not strictly enforced. In the vast majority of use-cases, one doesn’t care what the actual value of an enumeration is. But if the value is important, enumerations can have arbitrary values.
Enumerations are Python classes, and can have methods and special methods as usual. If we have this enumeration:
Then:
The rules for what is allowed are as follows: names that start and end with a single underscore are reserved by enum and cannot be used; all other attributes defined within an enumeration will become members of this enumeration, with the exception of special methods (__str__(), __add__(), etc.), descriptors (methods are also descriptors), and variable names listed in _ignore_.
Note: if your enumeration defines __new__() and/or __init__() then any value(s) given to the enum member will be passed into those methods. See Planet for an example.
A new Enum class must have one base Enum class, up to one concrete data type, and as many object-based mixin classes as needed. The order of these base classes is:
Also, subclassing an enumeration is allowed only if the enumeration does not define any members. So this is forbidden:
But this is allowed:
Allowing subclassing of enums that define members would lead to a violation of some important invariants of types and instances. On the other hand, it makes sense to allow sharing some common behavior between a group of enumerations. (See OrderedEnum for an example.)
Enumerations can be pickled and unpickled:
The usual restrictions for pickling apply: picklable enums must be defined in the top level of a module, since unpickling requires them to be importable from that module.
Note
With pickle protocol version 4 it is possible to easily pickle enums nested in other classes.
It is possible to modify how Enum members are pickled/unpickled by defining __reduce_ex__() in the enumeration class.
The Enum class is callable, providing the following functional API:
The semantics of this API resemble namedtuple. The first argument of the call to Enum is the name of the enumeration.
The second argument is the source of enumeration member names. It can be a whitespace-separated string of names, a sequence of names, a sequence of 2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to values. The last two options enable assigning arbitrary values to enumerations; the others auto-assign increasing integers starting with 1 (use the start parameter to specify a different starting value). A new class derived from Enum is returned. In other words, the above assignment to Animal is equivalent to:
The reason for defaulting to 1 as the starting number and not 0 is that 0 is False in a boolean sense, but enum members all evaluate to True.
Pickling enums created with the functional API can be tricky as frame stack implementation details are used to try and figure out which module the enumeration is being created in (e.g. it will fail if you use a utility function in separate module, and also may not work on IronPython or Jython). The solution is to specify the module name explicitly as follows:
Warning
If module is not supplied, and Enum cannot determine what it is, the new Enum members will not be unpicklable; to keep errors closer to the source, pickling will be disabled.
The new pickle protocol 4 also, in some circumstances, relies on __qualname__ being set to the location where pickle will be able to find the class. For example, if the class was made available in class SomeData in the global scope:
The complete signature is:
What the new Enum class will record as its name.
The Enum members. This can be a whitespace or comma separated string (values will start at 1 unless otherwise specified):
or an iterator of names:
or an iterator of (name, value) pairs:
or a mapping:
name of module where new Enum class can be found.
where in module new Enum class can be found.
type to mix in to new Enum class.
number to start counting at if only names are passed in.
Changed in version 3.5: The start parameter was added.
The first variation of Enum that is provided is also a subclass of int. Members of an IntEnum can be compared to integers; by extension, integer enumerations of different types can also be compared to each other:
However, they still can’t be compared to standard Enum enumerations:
IntEnum values behave like integers in other ways you’d expect:
The next variation of Enum provided, IntFlag, is also based on int. The difference being IntFlag members can be combined using the bitwise operators (&, |, ^, ~) and the result is still an IntFlag member. However, as the name implies, IntFlag members also subclass int and can be used wherever an int is used. Any operation on an IntFlag member besides the bit-wise operations will lose the IntFlag membership.
New in version 3.6.
Sample IntFlag class:
It is also possible to name the combinations:
Another important difference between IntFlag and Enum is that if no flags are set (the value is 0), its boolean evaluation is False:
Because IntFlag members are also subclasses of int they can be combined with them:
The last variation is Flag. Like IntFlag, Flag members can be combined using the bitwise operators (&, |, ^, ~). Unlike IntFlag, they cannot be combined with, nor compared against, any other Flag enumeration, nor int. While it is possible to specify the values directly it is recommended to use auto as the value and let Flag select an appropriate value.
New in version 3.6.
Like IntFlag, if a combination of Flag members results in no flags being set, the boolean evaluation is False:
Individual flags should have values that are powers of two (1, 2, 4, 8, …), while combinations of flags won’t:
Giving a name to the “no flags set” condition does not change its boolean value:
Note
For the majority of new code, Enum and Flag are strongly recommended, since IntEnum and IntFlag break some semantic promises of an enumeration (by being comparable to integers, and thus by transitivity to other unrelated enumerations). IntEnum and IntFlag should be used only in cases where Enum and Flag will not do; for example, when integer constants are replaced with enumerations, or for interoperability with other systems.
While IntEnum is part of the enum module, it would be very simple to implement independently:
This demonstrates how similar derived enumerations can be defined; for example a StrEnum that mixes in str instead of int.
Some rules:
__new__() must be used whenever you want to customize the actual value of the Enum member. Any other modifications may go in either __new__() or __init__(), with __init__() being preferred.
For example, if you want to pass several items to the constructor, but only want one of them to be the value:
While Enum, IntEnum, IntFlag, and Flag are expected to cover the majority of use-cases, they cannot cover them all. Here are recipes for some different types of enumerations that can be used directly, or as examples for creating one’s own.
In many use-cases one doesn’t care what the actual value of an enumeration is. There are several ways to define this type of simple enumeration:
Using any of these methods signifies to the user that these values are not important, and also enables one to add, remove, or reorder members without having to renumber the remaining members.
Whichever method you choose, you should provide a repr() that also hides the (unimportant) value:
Using auto would look like:
Using object would look like:
Using a string as the value would look like:
Using an auto-numbering __new__() would look like:
To make a more general purpose AutoNumber, add *args to the signature:
Then when you inherit from AutoNumber you can write your own __init__ to handle any extra arguments:
Note
The __new__() method, if defined, is used during creation of the Enum members; it is then replaced by Enum’s __new__() which is used after class creation for lookup of existing members.
An ordered enumeration that is not based on IntEnum and so maintains the normal Enum invariants (such as not being comparable to other enumerations):
Raises an error if a duplicate member name is found instead of creating an alias:
Note
This is a useful example for subclassing Enum to add or change other behaviors as well as disallowing aliases. If the only desired change is disallowing aliases, the unique() decorator can be used instead.
If __new__() or __init__() is defined the value of the enum member will be passed to those methods:
An example to show the _ignore_ attribute in use:
Enums have a custom metaclass that affects many aspects of both derived Enum classes and their instances (members).
The EnumMeta metaclass is responsible for providing the __contains__(), __dir__(), __iter__() and other methods that allow one to do things with an Enum class that fail on a typical class, such as list(Color) or some_enum_var in Color. EnumMeta is responsible for ensuring that various other methods on the final Enum class are correct (such as __new__(), __getnewargs__(), __str__() and __repr__()).
The most interesting thing about Enum members is that they are singletons. EnumMeta creates them all while it is creating the Enum class itself, and then puts a custom __new__() in place to ensure that no new ones are ever instantiated by returning only the existing member instances.
__members__ is a read-only ordered mapping of member_name:member items. It is only available on the class.
__new__(), if specified, must create and return the enum members; it is also a very good idea to set the member’s _value_ appropriately. Once all the members are created it is no longer used.
New in version 3.6: _missing_, _order_, _generate_next_value_
New in version 3.7: _ignore_
To help keep Python 2 / Python 3 code in sync an _order_ attribute can be provided. It will be checked against the actual order of the enumeration and raise an error if the two do not match:
Note
In Python 2 code the _order_ attribute is necessary as definition order is lost before it can be recorded.
Private names will be normal attributes in Python 3.10 instead of either an error or a member (depending on if the name ends with an underscore). Using these names in 3.9 will issue a DeprecationWarning.
Enum members are instances of their Enum class, and are normally accessed as EnumClass.member. Under certain circumstances they can also be accessed as EnumClass.member.member, but you should never do this as that lookup may fail or, worse, return something besides the Enum member you are looking for (this is another good reason to use all-uppercase names for members):
Changed in version 3.5.
Enum members that are mixed with non-Enum types (such as int, str, etc.) are evaluated according to the mixed-in type’s rules; otherwise, all members evaluate as True. To make your own Enum’s boolean evaluation depend on the member’s value add the following to your class:
Enum classes always evaluate as True.
If you give your Enum subclass extra methods, like the Planet class above, those methods will show up in a dir() of the member, but not of the class:
If a combination of Flag members is not named, the repr() will include all named flags and all named combinations of flags that are in the value:


Instances are replaced with an appropriate value for Enum members. By default, the initial value starts at 1.


Base class for creating enumerated constants. See section Functional API for an alternate construction syntax.


Base class for creating enumerated constants that can be combined using the bitwise operations without losing their Flag membership.


Base class for creating enumerated constants that are also subclasses of int.


Base class for creating enumerated constants that can be combined using the bitwise operators without losing their IntFlag membership. IntFlag members are also subclasses of int.


Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.
Equivalent to:


Raised when the input() function hits an end-of-file condition (EOF) without reading any data. (N.B.: the io.IOBase.read() and io.IOBase.readline() methods return an empty string when they hit EOF.)


This module makes available standard errno system symbols. The value of each symbol is the corresponding integer value. The names and descriptions are borrowed from linux/include/errno.h, which should be pretty all-inclusive.
Dictionary providing a mapping from the errno value to the string name in the underlying system. For instance, errno.errorcode[errno.EPERM] maps to 'EPERM'.
To translate a numeric error code to an error message, use os.strerror().
Of the following list, symbols that are not used on the current platform are not defined by the module. The specific list of defined symbols is available as errno.errorcode.keys(). Symbols available can include:
Operation not permitted
No such file or directory
No such process
Interrupted system call.
See also
This error is mapped to the exception InterruptedError.
I/O error
No such device or address
Arg list too long
Exec format error
Bad file number
No child processes
Try again
Out of memory
Permission denied
Bad address
Block device required
Device or resource busy
File exists
Cross-device link
No such device
Not a directory
Is a directory
Invalid argument
File table overflow
Too many open files
Not a typewriter
Text file busy
File too large
No space left on device
Illegal seek
Read-only file system
Too many links
Broken pipe
Math argument out of domain of func
Math result not representable
Resource deadlock would occur
File name too long
No record locks available
Function not implemented
Directory not empty
Too many symbolic links encountered
Operation would block
No message of desired type
Identifier removed
Channel number out of range
Level 2 not synchronized
Level 3 halted
Level 3 reset
Link number out of range
Protocol driver not attached
No CSI structure available
Level 2 halted
Invalid exchange
Invalid request descriptor
Exchange full
No anode
Invalid request code
Invalid slot
File locking deadlock error
Bad font file format
Device not a stream
No data available
Timer expired
Out of streams resources
Machine is not on the network
Package not installed
Object is remote
Link has been severed
Advertise error
Srmount error
Communication error on send
Protocol error
Multihop attempted
RFS specific error
Not a data message
Value too large for defined data type
Name not unique on network
File descriptor in bad state
Remote address changed
Can not access a needed shared library
Accessing a corrupted shared library
.lib section in a.out corrupted
Attempting to link in too many shared libraries
Cannot exec a shared library directly
Illegal byte sequence
Interrupted system call should be restarted
Streams pipe error
Too many users
Socket operation on non-socket
Destination address required
Message too long
Protocol wrong type for socket
Protocol not available
Protocol not supported
Socket type not supported
Operation not supported on transport endpoint
Protocol family not supported
Address family not supported by protocol
Address already in use
Cannot assign requested address
Network is down
Network is unreachable
Network dropped connection because of reset
Software caused connection abort
Connection reset by peer
No buffer space available
Transport endpoint is already connected
Transport endpoint is not connected
Cannot send after transport endpoint shutdown
Too many references: cannot splice
Connection timed out
Connection refused
Host is down
No route to host
Operation already in progress
Operation now in progress
Stale NFS file handle
Structure needs cleaning
Not a XENIX named type file
No XENIX semaphores available
Is a named type file
Remote I/O error
Quota exceeded


The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.
The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key before expression is parsed. This means that expression normally has full access to the standard builtins module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed with the globals and locals in the environment where eval() is called. Note, eval() does not have access to the nested scopes (non-locals) in the enclosing environment.
The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:
This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval()’s return value will be None.
Hints: dynamic execution of statements is supported by the exec() function. The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec().
See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.
Raises an auditing event exec with the code object as the argument. Code compilation events may also be raised.


All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.


Source code: Lib/asyncio/exceptions.py
The operation has exceeded the given deadline.
Important
This exception is different from the builtin TimeoutError exception.
The operation has been cancelled.
This exception can be caught to perform custom operations when asyncio Tasks are cancelled. In almost all situations the exception must be re-raised.
Changed in version 3.8: CancelledError is now a subclass of BaseException.
Invalid internal state of Task or Future.
Can be raised in situations like setting a result value for a Future object that already has a result value set.
The “sendfile” syscall is not available for the given socket or file type.
A subclass of RuntimeError.
The requested read operation did not complete fully.
Raised by the asyncio stream APIs.
This exception is a subclass of EOFError.
The total number (int) of expected bytes.
A string of bytes read before the end of stream was reached.
Reached the buffer size limit while looking for a separator.
Raised by the asyncio stream APIs.
The total number of to be consumed bytes.


In Python, all exceptions must be instances of a class that derives from BaseException. In a try statement with an except clause that mentions a particular class, that clause also handles any exception classes derived from that class (but not exception classes from which it is derived). Two exception classes that are not related via subclassing are never equivalent, even if they have the same name.
The built-in exceptions listed below can be generated by the interpreter or built-in functions. Except where mentioned, they have an “associated value” indicating the detailed cause of the error. This may be a string or a tuple of several items of information (e.g., an error code and a string explaining the code). The associated value is usually passed as arguments to the exception class’s constructor.
User code can raise built-in exceptions. This can be used to test an exception handler or to report an error condition “just like” the situation in which the interpreter raises the same exception; but beware that there is nothing to prevent user code from raising an inappropriate error.
The built-in exception classes can be subclassed to define new exceptions; programmers are encouraged to derive new exceptions from the Exception class or one of its subclasses, and not from BaseException. More information on defining exceptions is available in the Python Tutorial under User-defined Exceptions.
When raising (or re-raising) an exception in an except or finally clause __context__ is automatically set to the last exception caught; if the new exception is not handled the traceback that is eventually displayed will include the originating exception(s) and the final exception.
When raising a new exception (rather than using a bare raise to re-raise the exception currently being handled), the implicit exception context can be supplemented with an explicit cause by using from with raise:
The expression following from must be an exception or None. It will be set as __cause__ on the raised exception. Setting __cause__ also implicitly sets the __suppress_context__ attribute to True, so that using raise new_exc from None effectively replaces the old exception with the new one for display purposes (e.g. converting KeyError to AttributeError), while leaving the old exception available in __context__ for introspection when debugging.
The default traceback display code shows these chained exceptions in addition to the traceback for the exception itself. An explicitly chained exception in __cause__ is always shown when present. An implicitly chained exception in __context__ is shown only if __cause__ is None and __suppress_context__ is false.
In either case, the exception itself is always shown after any chained exceptions so that the final line of the traceback always shows the last exception that was raised.
The following exceptions are used mostly as base classes for other exceptions.
The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that, use Exception). If str() is called on an instance of this class, the representation of the argument(s) to the instance are returned, or the empty string when there were no arguments.
The tuple of arguments given to the exception constructor. Some built-in exceptions (like OSError) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message.
This method sets tb as the new traceback for the exception and returns the exception object. It is usually used in exception handling code like this:
All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.
The base class for those built-in exceptions that are raised for various arithmetic errors: OverflowError, ZeroDivisionError, FloatingPointError.
Raised when a buffer related operation cannot be performed.
The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError. This can be raised directly by codecs.lookup().
The following exceptions are the exceptions that are usually raised.
Raised when an assert statement fails.
Raised when an attribute reference (see Attribute references) or assignment fails. (When an object does not support attribute references or attribute assignments at all, TypeError is raised.)
Raised when the input() function hits an end-of-file condition (EOF) without reading any data. (N.B.: the io.IOBase.read() and io.IOBase.readline() methods return an empty string when they hit EOF.)
Not currently used.
Raised when a generator or coroutine is closed; see generator.close() and coroutine.close(). It directly inherits from BaseException instead of Exception since it is technically not an error.
Raised when the import statement has troubles trying to load a module. Also raised when the “from list” in from ... import has a name that cannot be found.
The name and path attributes can be set using keyword-only arguments to the constructor. When set they represent the name of the module that was attempted to be imported and the path to any file which triggered the exception, respectively.
Changed in version 3.3: Added the name and path attributes.
A subclass of ImportError which is raised by import when a module could not be located. It is also raised when None is found in sys.modules.
New in version 3.6.
Raised when a sequence subscript is out of range. (Slice indices are silently truncated to fall in the allowed range; if an index is not an integer, TypeError is raised.)
Raised when a mapping (dictionary) key is not found in the set of existing keys.
Raised when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly. The exception inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting.
Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects). The associated value is a string indicating what kind of (internal) operation ran out of memory. Note that because of the underlying memory management architecture (C’s malloc() function), the interpreter may not always be able to completely recover from this situation; it nevertheless raises an exception so that a stack traceback can be printed, in case a run-away program was the cause.
Raised when a local or global name is not found. This applies only to unqualified names. The associated value is an error message that includes the name that could not be found.
This exception is derived from RuntimeError. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method, or while the class is being developed to indicate that the real implementation still needs to be added.
Note
It should not be used to indicate that an operator or method is not meant to be supported at all – in that case either leave the operator / method undefined or, if a subclass, set it to None.
Note
NotImplementedError and NotImplemented are not interchangeable, even though they have similar names and purposes. See NotImplemented for details on when to use it.
This exception is raised when a system function returns a system-related error, including I/O failures such as “file not found” or “disk full” (not for illegal argument types or other incidental errors).
The second form of the constructor sets the corresponding attributes, described below. The attributes default to None if not specified. For backwards compatibility, if three arguments are passed, the args attribute contains only a 2-tuple of the first two constructor arguments.
The constructor often actually returns a subclass of OSError, as described in OS exceptions below. The particular subclass depends on the final errno value. This behaviour only occurs when constructing OSError directly or via an alias, and is not inherited when subclassing.
A numeric error code from the C variable errno.
Under Windows, this gives you the native Windows error code. The errno attribute is then an approximate translation, in POSIX terms, of that native error code.
Under Windows, if the winerror constructor argument is an integer, the errno attribute is determined from the Windows error code, and the errno argument is ignored. On other platforms, the winerror argument is ignored, and the winerror attribute does not exist.
The corresponding error message, as provided by the operating system. It is formatted by the C functions perror() under POSIX, and FormatMessage() under Windows.
For exceptions that involve a file system path (such as open() or os.unlink()), filename is the file name passed to the function. For functions that involve two file system paths (such as os.rename()), filename2 corresponds to the second file name passed to the function.
Changed in version 3.3: EnvironmentError, IOError, WindowsError, socket.error, select.error and mmap.error have been merged into OSError, and the constructor may return a subclass.
Changed in version 3.4: The filename attribute is now the original file name passed to the function, instead of the name encoded to or decoded from the filesystem encoding. Also, the filename2 constructor argument and attribute was added.
Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for integers (which would rather raise MemoryError than give up). However, for historical reasons, OverflowError is sometimes raised for integers that are outside a required range. Because of the lack of standardization of floating point exception handling in C, most floating point operations are not checked.
This exception is derived from RuntimeError. It is raised when the interpreter detects that the maximum recursion depth (see sys.getrecursionlimit()) is exceeded.
New in version 3.5: Previously, a plain RuntimeError was raised.
This exception is raised when a weak reference proxy, created by the weakref.proxy() function, is used to access an attribute of the referent after it has been garbage collected. For more information on weak references, see the weakref module.
Raised when an error is detected that doesn’t fall in any of the other categories. The associated value is a string indicating what precisely went wrong.
Raised by built-in function next() and an iterator’s __next__() method to signal that there are no further items produced by the iterator.
The exception object has a single attribute value, which is given as an argument when constructing the exception, and defaults to None.
When a generator or coroutine function returns, a new StopIteration instance is raised, and the value returned by the function is used as the value parameter to the constructor of the exception.
If a generator code directly or indirectly raises StopIteration, it is converted into a RuntimeError (retaining the StopIteration as the new exception’s cause).
Changed in version 3.3: Added value attribute and the ability for generator functions to use it to return a value.
Changed in version 3.5: Introduced the RuntimeError transformation via from __future__ import generator_stop, see PEP 479.
Changed in version 3.7: Enable PEP 479 for all code by default: a StopIteration error raised in a generator is transformed into a RuntimeError.
Must be raised by __anext__() method of an asynchronous iterator object to stop the iteration.
New in version 3.5.
Raised when the parser encounters a syntax error. This may occur in an import statement, in a call to the built-in functions exec() or eval(), or when reading the initial script or standard input (also interactively).
The str() of the exception instance returns only the error message.
The name of the file the syntax error occurred in.
Which line number in the file the error occurred in. This is 1-indexed: the first line in the file has a lineno of 1.
The column in the line where the error occurred. This is 1-indexed: the first character in the line has an offset of 1.
The source code text involved in the error.
Base class for syntax errors related to incorrect indentation. This is a subclass of SyntaxError.
Raised when indentation contains an inconsistent use of tabs and spaces. This is a subclass of IndentationError.
Raised when the interpreter finds an internal error, but the situation does not look so serious to cause it to abandon all hope. The associated value is a string indicating what went wrong (in low-level terms).
You should report this to the author or maintainer of your Python interpreter. Be sure to report the version of the Python interpreter (sys.version; it is also printed at the start of an interactive Python session), the exact error message (the exception’s associated value) and if possible the source of the program that triggered the error.
This exception is raised by the sys.exit() function. It inherits from BaseException instead of Exception so that it is not accidentally caught by code that catches Exception. This allows the exception to properly propagate up and cause the interpreter to exit. When it is not handled, the Python interpreter exits; no stack traceback is printed. The constructor accepts the same optional argument passed to sys.exit(). If the value is an integer, it specifies the system exit status (passed to C’s exit() function); if it is None, the exit status is zero; if it has another type (such as a string), the object’s value is printed and the exit status is one.
A call to sys.exit() is translated into an exception so that clean-up handlers (finally clauses of try statements) can be executed, and so that a debugger can execute a script without running the risk of losing control. The os._exit() function can be used if it is absolutely positively necessary to exit immediately (for example, in the child process after a call to os.fork()).
The exit status or error message that is passed to the constructor. (Defaults to None.)
Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.
This exception may be raised by user code to indicate that an attempted operation on an object is not supported, and is not meant to be. If an object is meant to support a given operation but has not yet provided an implementation, NotImplementedError is the proper exception to raise.
Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError.
Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. This is a subclass of NameError.
Raised when a Unicode-related encoding or decoding error occurs. It is a subclass of ValueError.
UnicodeError has attributes that describe the encoding or decoding error. For example, err.object[err.start:err.end] gives the particular invalid input that the codec failed on.
The name of the encoding that raised the error.
A string describing the specific codec error.
The object the codec was attempting to encode or decode.
The first index of invalid data in object.
The index after the last invalid data in object.
Raised when a Unicode-related error occurs during encoding. It is a subclass of UnicodeError.
Raised when a Unicode-related error occurs during decoding. It is a subclass of UnicodeError.
Raised when a Unicode-related error occurs during translating. It is a subclass of UnicodeError.
Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
Raised when the second argument of a division or modulo operation is zero. The associated value is a string indicating the type of the operands and the operation.
The following exceptions are kept for compatibility with previous versions; starting from Python 3.3, they are aliases of OSError.
Only available on Windows.
The following exceptions are subclasses of OSError, they get raised depending on the system error code.
Raised when an operation would block on an object (e.g. socket) set for non-blocking operation. Corresponds to errno EAGAIN, EALREADY, EWOULDBLOCK and EINPROGRESS.
In addition to those of OSError, BlockingIOError can have one more attribute:
An integer containing the number of characters written to the stream before it blocked. This attribute is available when using the buffered I/O classes from the io module.
Raised when an operation on a child process failed. Corresponds to errno ECHILD.
A base class for connection-related issues.
Subclasses are BrokenPipeError, ConnectionAbortedError, ConnectionRefusedError and ConnectionResetError.
A subclass of ConnectionError, raised when trying to write on a pipe while the other end has been closed, or trying to write on a socket which has been shutdown for writing. Corresponds to errno EPIPE and ESHUTDOWN.
A subclass of ConnectionError, raised when a connection attempt is aborted by the peer. Corresponds to errno ECONNABORTED.
A subclass of ConnectionError, raised when a connection attempt is refused by the peer. Corresponds to errno ECONNREFUSED.
A subclass of ConnectionError, raised when a connection is reset by the peer. Corresponds to errno ECONNRESET.
Raised when trying to create a file or directory which already exists. Corresponds to errno EEXIST.
Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.
Raised when a system call is interrupted by an incoming signal. Corresponds to errno EINTR.
Changed in version 3.5: Python now retries system calls when a syscall is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising InterruptedError.
Raised when a file operation (such as os.remove()) is requested on a directory. Corresponds to errno EISDIR.
Raised when a directory operation (such as os.listdir()) is requested on something which is not a directory. Corresponds to errno ENOTDIR.
Raised when trying to run an operation without the adequate access rights - for example filesystem permissions. Corresponds to errno EACCES and EPERM.
Raised when a given process doesn’t exist. Corresponds to errno ESRCH.
Raised when a system function timed out at the system level. Corresponds to errno ETIMEDOUT.
New in version 3.3: All the above OSError subclasses were added.
See also
PEP 3151 - Reworking the OS and IO exception hierarchy
The following exceptions are used as warning categories; see the Warning Categories documentation for more details.
Base class for warning categories.
Base class for warnings generated by user code.
Base class for warnings about deprecated features when those warnings are intended for other Python developers.
Ignored by the default warning filters, except in the __main__ module (PEP 565). Enabling the Python Development Mode shows this warning.
Base class for warnings about features which are obsolete and expected to be deprecated in the future, but are not deprecated at the moment.
This class is rarely used as emitting a warning about a possible upcoming deprecation is unusual, and DeprecationWarning is preferred for already active deprecations.
Ignored by the default warning filters. Enabling the Python Development Mode shows this warning.
Base class for warnings about dubious syntax.
Base class for warnings about dubious runtime behavior.
Base class for warnings about deprecated features when those warnings are intended for end users of applications that are written in Python.
Base class for warnings about probable mistakes in module imports.
Ignored by the default warning filters. Enabling the Python Development Mode shows this warning.
Base class for warnings related to Unicode.
Base class for warnings related to bytes and bytearray.
Base class for warnings related to resource usage.
Ignored by the default warning filters. Enabling the Python Development Mode shows this warning.
New in version 3.2.
The class hierarchy for built-in exceptions is:


This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). 1 If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section “File input” in the Reference Manual). Be aware that the nonlocal, yield, and return statements may not be used outside of function definitions even within the context of code passed to the exec() function. The return value is None.
In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary (and not a subclass of dictionary), which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.
If the globals dictionary does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own __builtins__ dictionary into globals before passing it to exec().
Raises an auditing event exec with the code object as the argument. Code compilation events may also be raised.
Note
The built-in functions globals() and locals() return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to exec().
Note
The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.


Objects that when printed, print a message like “Use quit() or Ctrl-D (i.e. EOF) to exit”, and when called, raise SystemExit with the specified exit code.


The false value of the bool type. Assignments to False are illegal and raise a SyntaxError.


New in version 3.3.
This module contains functions to dump Python tracebacks explicitly, on a fault, after a timeout, or on a user signal. Call faulthandler.enable() to install fault handlers for the SIGSEGV, SIGFPE, SIGABRT, SIGBUS, and SIGILL signals. You can also enable them at startup by setting the PYTHONFAULTHANDLER environment variable or by using the -X faulthandler command line option.
The fault handler is compatible with system fault handlers like Apport or the Windows fault handler. The module uses an alternative stack for signal handlers if the sigaltstack() function is available. This allows it to dump the traceback even on a stack overflow.
The fault handler is called on catastrophic cases and therefore can only use signal-safe functions (e.g. it cannot allocate memory on the heap). Because of this limitation traceback dumping is minimal compared to normal Python tracebacks:
By default, the Python traceback is written to sys.stderr. To see tracebacks, applications must be run in the terminal. A log file can alternatively be passed to faulthandler.enable().
The module is implemented in C, so tracebacks can be dumped on a crash or when Python is deadlocked.
The Python Development Mode calls faulthandler.enable() at Python startup.
Dump the tracebacks of all threads into file. If all_threads is False, dump only the current thread.
Changed in version 3.5: Added support for passing file descriptor to this function.
Enable the fault handler: install handlers for the SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals to dump the Python traceback. If all_threads is True, produce tracebacks for every running thread. Otherwise, dump only the current thread.
The file must be kept open until the fault handler is disabled: see issue with file descriptors.
Changed in version 3.5: Added support for passing file descriptor to this function.
Changed in version 3.6: On Windows, a handler for Windows exception is also installed.
Disable the fault handler: uninstall the signal handlers installed by enable().
Check if the fault handler is enabled.
Dump the tracebacks of all threads, after a timeout of timeout seconds, or every timeout seconds if repeat is True. If exit is True, call _exit() with status=1 after dumping the tracebacks. (Note _exit() exits the process immediately, which means it doesn’t do any cleanup like flushing file buffers.) If the function is called twice, the new call replaces previous parameters and resets the timeout. The timer has a sub-second resolution.
The file must be kept open until the traceback is dumped or cancel_dump_traceback_later() is called: see issue with file descriptors.
This function is implemented using a watchdog thread.
Changed in version 3.7: This function is now always available.
Changed in version 3.5: Added support for passing file descriptor to this function.
Cancel the last call to dump_traceback_later().
Register a user signal: install a handler for the signum signal to dump the traceback of all threads, or of the current thread if all_threads is False, into file. Call the previous handler if chain is True.
The file must be kept open until the signal is unregistered by unregister(): see issue with file descriptors.
Not available on Windows.
Changed in version 3.5: Added support for passing file descriptor to this function.
Unregister a user signal: uninstall the handler of the signum signal installed by register(). Return True if the signal was registered, False otherwise.
Not available on Windows.
enable(), dump_traceback_later() and register() keep the file descriptor of their file argument. If the file is closed and its file descriptor is reused by a new file, or if os.dup2() is used to replace the file descriptor, the traceback will be written into a different file. Call these functions again each time that the file is replaced.
Example of a segmentation fault on Linux with and without enabling the fault handler:


Cancel the last call to dump_traceback_later().


Disable the fault handler: uninstall the signal handlers installed by enable().


Dump the tracebacks of all threads into file. If all_threads is False, dump only the current thread.
Changed in version 3.5: Added support for passing file descriptor to this function.


Dump the tracebacks of all threads, after a timeout of timeout seconds, or every timeout seconds if repeat is True. If exit is True, call _exit() with status=1 after dumping the tracebacks. (Note _exit() exits the process immediately, which means it doesn’t do any cleanup like flushing file buffers.) If the function is called twice, the new call replaces previous parameters and resets the timeout. The timer has a sub-second resolution.
The file must be kept open until the traceback is dumped or cancel_dump_traceback_later() is called: see issue with file descriptors.
This function is implemented using a watchdog thread.
Changed in version 3.7: This function is now always available.
Changed in version 3.5: Added support for passing file descriptor to this function.


Enable the fault handler: install handlers for the SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals to dump the Python traceback. If all_threads is True, produce tracebacks for every running thread. Otherwise, dump only the current thread.
The file must be kept open until the fault handler is disabled: see issue with file descriptors.
Changed in version 3.5: Added support for passing file descriptor to this function.
Changed in version 3.6: On Windows, a handler for Windows exception is also installed.


Register a user signal: install a handler for the signum signal to dump the traceback of all threads, or of the current thread if all_threads is False, into file. Call the previous handler if chain is True.
The file must be kept open until the signal is unregistered by unregister(): see issue with file descriptors.
Not available on Windows.
Changed in version 3.5: Added support for passing file descriptor to this function.


Unregister a user signal: uninstall the handler of the signum signal installed by register(). Return True if the signal was registered, False otherwise.
Not available on Windows.


This module performs file control and I/O control on file descriptors. It is an interface to the fcntl() and ioctl() Unix routines. For a complete description of these calls, see fcntl(2) and ioctl(2) Unix manual pages.
All functions in this module take a file descriptor fd as their first argument. This can be an integer file descriptor, such as returned by sys.stdin.fileno(), or an io.IOBase object, such as sys.stdin itself, which provides a fileno() that returns a genuine file descriptor.
Changed in version 3.3: Operations in this module used to raise an IOError where they now raise an OSError.
Changed in version 3.8: The fcntl module now contains F_ADD_SEALS, F_GET_SEALS, and F_SEAL_* constants for sealing of os.memfd_create() file descriptors.
Changed in version 3.9: On macOS, the fcntl module exposes the F_GETPATH constant, which obtains the path of a file from a file descriptor. On Linux(>=3.15), the fcntl module exposes the F_OFD_GETLK, F_OFD_SETLK and F_OFD_SETLKW constants, which working with open file description locks.
The module defines the following functions:
Perform the operation cmd on file descriptor fd (file objects providing a fileno() method are accepted as well). The values used for cmd are operating system dependent, and are available as constants in the fcntl module, using the same names as used in the relevant C header files. The argument arg can either be an integer value, or a bytes object. With an integer value, the return value of this function is the integer return value of the C fcntl() call. When the argument is bytes it represents a binary structure, e.g. created by struct.pack(). The binary data is copied to a buffer whose address is passed to the C fcntl() call. The return value after a successful call is the contents of the buffer, converted to a bytes object. The length of the returned object will be the same as the length of the arg argument. This is limited to 1024 bytes. If the information returned in the buffer by the operating system is larger than 1024 bytes, this is most likely to result in a segmentation violation or a more subtle data corruption.
If the fcntl() fails, an OSError is raised.
Raises an auditing event fcntl.fcntl with arguments fd, cmd, arg.
This function is identical to the fcntl() function, except that the argument handling is even more complicated.
The request parameter is limited to values that can fit in 32-bits. Additional constants of interest for use as the request argument can be found in the termios module, under the same names as used in the relevant C header files.
The parameter arg can be one of an integer, an object supporting the read-only buffer interface (like bytes) or an object supporting the read-write buffer interface (like bytearray).
In all but the last case, behaviour is as for the fcntl() function.
If a mutable buffer is passed, then the behaviour is determined by the value of the mutate_flag parameter.
If it is false, the buffer’s mutability is ignored and behaviour is as for a read-only buffer, except that the 1024 byte limit mentioned above is avoided – so long as the buffer you pass is at least as long as what the operating system wants to put there, things should work.
If mutate_flag is true (the default), then the buffer is (in effect) passed to the underlying ioctl() system call, the latter’s return code is passed back to the calling Python, and the buffer’s new contents reflect the action of the ioctl(). This is a slight simplification, because if the supplied buffer is less than 1024 bytes long it is first copied into a static buffer 1024 bytes long which is then passed to ioctl() and copied back into the supplied buffer.
If the ioctl() fails, an OSError exception is raised.
An example:
Raises an auditing event fcntl.ioctl with arguments fd, request, arg.
Perform the lock operation operation on file descriptor fd (file objects providing a fileno() method are accepted as well). See the Unix manual flock(2) for details. (On some systems, this function is emulated using fcntl().)
If the flock() fails, an OSError exception is raised.
Raises an auditing event fcntl.flock with arguments fd, operation.
This is essentially a wrapper around the fcntl() locking calls. fd is the file descriptor (file objects providing a fileno() method are accepted as well) of the file to lock or unlock, and cmd is one of the following values:
When cmd is LOCK_SH or LOCK_EX, it can also be bitwise ORed with LOCK_NB to avoid blocking on lock acquisition. If LOCK_NB is used and the lock cannot be acquired, an OSError will be raised and the exception will have an errno attribute set to EACCES or EAGAIN (depending on the operating system; for portability, check for both values). On at least some systems, LOCK_EX can only be used if the file descriptor refers to a file opened for writing.
len is the number of bytes to lock, start is the byte offset at which the lock starts, relative to whence, and whence is as with io.IOBase.seek(), specifically:
The default for start is 0, which means to start at the beginning of the file. The default for len is 0 which means to lock to the end of the file. The default for whence is also 0.
Raises an auditing event fcntl.lockf with arguments fd, cmd, len, start, whence.
Examples (all on a SVR4 compliant system):
Note that in the first example the return value variable rv will hold an integer value; in the second example it will hold a bytes object. The structure lay-out for the lockdata variable is system dependent — therefore using the flock() call may be better.
See also
If the locking flags O_SHLOCK and O_EXLOCK are present in the os module (on BSD only), the os.open() function provides an alternative to the lockf() and flock() functions.


Perform the operation cmd on file descriptor fd (file objects providing a fileno() method are accepted as well). The values used for cmd are operating system dependent, and are available as constants in the fcntl module, using the same names as used in the relevant C header files. The argument arg can either be an integer value, or a bytes object. With an integer value, the return value of this function is the integer return value of the C fcntl() call. When the argument is bytes it represents a binary structure, e.g. created by struct.pack(). The binary data is copied to a buffer whose address is passed to the C fcntl() call. The return value after a successful call is the contents of the buffer, converted to a bytes object. The length of the returned object will be the same as the length of the arg argument. This is limited to 1024 bytes. If the information returned in the buffer by the operating system is larger than 1024 bytes, this is most likely to result in a segmentation violation or a more subtle data corruption.
If the fcntl() fails, an OSError is raised.
Raises an auditing event fcntl.fcntl with arguments fd, cmd, arg.


Perform the lock operation operation on file descriptor fd (file objects providing a fileno() method are accepted as well). See the Unix manual flock(2) for details. (On some systems, this function is emulated using fcntl().)
If the flock() fails, an OSError exception is raised.
Raises an auditing event fcntl.flock with arguments fd, operation.


This function is identical to the fcntl() function, except that the argument handling is even more complicated.
The request parameter is limited to values that can fit in 32-bits. Additional constants of interest for use as the request argument can be found in the termios module, under the same names as used in the relevant C header files.
The parameter arg can be one of an integer, an object supporting the read-only buffer interface (like bytes) or an object supporting the read-write buffer interface (like bytearray).
In all but the last case, behaviour is as for the fcntl() function.
If a mutable buffer is passed, then the behaviour is determined by the value of the mutate_flag parameter.
If it is false, the buffer’s mutability is ignored and behaviour is as for a read-only buffer, except that the 1024 byte limit mentioned above is avoided – so long as the buffer you pass is at least as long as what the operating system wants to put there, things should work.
If mutate_flag is true (the default), then the buffer is (in effect) passed to the underlying ioctl() system call, the latter’s return code is passed back to the calling Python, and the buffer’s new contents reflect the action of the ioctl(). This is a slight simplification, because if the supplied buffer is less than 1024 bytes long it is first copied into a static buffer 1024 bytes long which is then passed to ioctl() and copied back into the supplied buffer.
If the ioctl() fails, an OSError exception is raised.
An example:
Raises an auditing event fcntl.ioctl with arguments fd, request, arg.


This is essentially a wrapper around the fcntl() locking calls. fd is the file descriptor (file objects providing a fileno() method are accepted as well) of the file to lock or unlock, and cmd is one of the following values:
When cmd is LOCK_SH or LOCK_EX, it can also be bitwise ORed with LOCK_NB to avoid blocking on lock acquisition. If LOCK_NB is used and the lock cannot be acquired, an OSError will be raised and the exception will have an errno attribute set to EACCES or EAGAIN (depending on the operating system; for portability, check for both values). On at least some systems, LOCK_EX can only be used if the file descriptor refers to a file opened for writing.
len is the number of bytes to lock, start is the byte offset at which the lock starts, relative to whence, and whence is as with io.IOBase.seek(), specifically:
The default for start is 0, which means to start at the beginning of the file. The default for len is 0 which means to lock to the end of the file. The default for whence is also 0.
Raises an auditing event fcntl.lockf with arguments fd, cmd, len, start, whence.


Source code: Lib/filecmp.py
The filecmp module defines functions to compare files and directories, with various optional time/correctness trade-offs. For comparing files, see also the difflib module.
The filecmp module defines the following functions:
Compare the files named f1 and f2, returning True if they seem equal, False otherwise.
If shallow is true, files with identical os.stat() signatures are taken to be equal. Otherwise, the contents of the files are compared.
Note that no external programs are called from this function, giving it portability and efficiency.
This function uses a cache for past comparisons and the results, with cache entries invalidated if the os.stat() information for the file changes. The entire cache may be cleared using clear_cache().
Compare the files in the two directories dir1 and dir2 whose names are given by common.
Returns three lists of file names: match, mismatch, errors. match contains the list of files that match, mismatch contains the names of those that don’t, and errors lists the names of files which could not be compared. Files are listed in errors if they don’t exist in one of the directories, the user lacks permission to read them or if the comparison could not be done for some other reason.
The shallow parameter has the same meaning and default value as for filecmp.cmp().
For example, cmpfiles('a', 'b', ['c', 'd/e']) will compare a/c with b/c and a/d/e with b/d/e. 'c' and 'd/e' will each be in one of the three returned lists.
Clear the filecmp cache. This may be useful if a file is compared so quickly after it is modified that it is within the mtime resolution of the underlying filesystem.
New in version 3.4.
Construct a new directory comparison object, to compare the directories a and b. ignore is a list of names to ignore, and defaults to filecmp.DEFAULT_IGNORES. hide is a list of names to hide, and defaults to [os.curdir, os.pardir].
The dircmp class compares files by doing shallow comparisons as described for filecmp.cmp().
The dircmp class provides the following methods:
Print (to sys.stdout) a comparison between a and b.
Print a comparison between a and b and common immediate subdirectories.
Print a comparison between a and b and common subdirectories (recursively).
The dircmp class offers a number of interesting attributes that may be used to get various bits of information about the directory trees being compared.
Note that via __getattr__() hooks, all attributes are computed lazily, so there is no speed penalty if only those attributes which are lightweight to compute are used.
The directory a.
The directory b.
Files and subdirectories in a, filtered by hide and ignore.
Files and subdirectories in b, filtered by hide and ignore.
Files and subdirectories in both a and b.
Files and subdirectories only in a.
Files and subdirectories only in b.
Subdirectories in both a and b.
Files in both a and b.
Names in both a and b, such that the type differs between the directories, or names for which os.stat() reports an error.
Files which are identical in both a and b, using the class’s file comparison operator.
Files which are in both a and b, whose contents differ according to the class’s file comparison operator.
Files which are in both a and b, but could not be compared.
A dictionary mapping names in common_dirs to dircmp objects.
New in version 3.4.
List of directories ignored by dircmp by default.
Here is a simplified example of using the subdirs attribute to search recursively through two directories to show common different files:


Clear the filecmp cache. This may be useful if a file is compared so quickly after it is modified that it is within the mtime resolution of the underlying filesystem.
New in version 3.4.


Compare the files named f1 and f2, returning True if they seem equal, False otherwise.
If shallow is true, files with identical os.stat() signatures are taken to be equal. Otherwise, the contents of the files are compared.
Note that no external programs are called from this function, giving it portability and efficiency.
This function uses a cache for past comparisons and the results, with cache entries invalidated if the os.stat() information for the file changes. The entire cache may be cleared using clear_cache().


Compare the files in the two directories dir1 and dir2 whose names are given by common.
Returns three lists of file names: match, mismatch, errors. match contains the list of files that match, mismatch contains the names of those that don’t, and errors lists the names of files which could not be compared. Files are listed in errors if they don’t exist in one of the directories, the user lacks permission to read them or if the comparison could not be done for some other reason.
The shallow parameter has the same meaning and default value as for filecmp.cmp().
For example, cmpfiles('a', 'b', ['c', 'd/e']) will compare a/c with b/c and a/d/e with b/d/e. 'c' and 'd/e' will each be in one of the three returned lists.


New in version 3.4.
List of directories ignored by dircmp by default.


Construct a new directory comparison object, to compare the directories a and b. ignore is a list of names to ignore, and defaults to filecmp.DEFAULT_IGNORES. hide is a list of names to hide, and defaults to [os.curdir, os.pardir].
The dircmp class compares files by doing shallow comparisons as described for filecmp.cmp().
The dircmp class provides the following methods:
Print (to sys.stdout) a comparison between a and b.
Print a comparison between a and b and common immediate subdirectories.
Print a comparison between a and b and common subdirectories (recursively).
The dircmp class offers a number of interesting attributes that may be used to get various bits of information about the directory trees being compared.
Note that via __getattr__() hooks, all attributes are computed lazily, so there is no speed penalty if only those attributes which are lightweight to compute are used.
The directory a.
The directory b.
Files and subdirectories in a, filtered by hide and ignore.
Files and subdirectories in b, filtered by hide and ignore.
Files and subdirectories in both a and b.
Files and subdirectories only in a.
Files and subdirectories only in b.
Subdirectories in both a and b.
Files in both a and b.
Names in both a and b, such that the type differs between the directories, or names for which os.stat() reports an error.
Files which are identical in both a and b, using the class’s file comparison operator.
Files which are in both a and b, whose contents differ according to the class’s file comparison operator.
Files which are in both a and b, but could not be compared.
A dictionary mapping names in common_dirs to dircmp objects.


Files and subdirectories in both a and b.


Names in both a and b, such that the type differs between the directories, or names for which os.stat() reports an error.


Files which are in both a and b, whose contents differ according to the class’s file comparison operator.


Files which are in both a and b, but could not be compared.


Files and subdirectories in a, filtered by hide and ignore.


Print (to sys.stdout) a comparison between a and b.


Print a comparison between a and b and common subdirectories (recursively).


Print a comparison between a and b and common immediate subdirectories.


Files and subdirectories in b, filtered by hide and ignore.


Files which are identical in both a and b, using the class’s file comparison operator.


A dictionary mapping names in common_dirs to dircmp objects.


Raised when trying to create a file or directory which already exists. Corresponds to errno EEXIST.


Source code: Lib/fileinput.py
This module implements a helper class and functions to quickly write a loop over standard input or a list of files. If you just want to read or write one file see open().
The typical use is:
This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin and the optional arguments mode and openhook are ignored. To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed.
All files are opened in text mode by default, but you can override this by specifying the mode parameter in the call to input() or FileInput. If an I/O error occurs during opening or reading a file, OSError is raised.
Changed in version 3.3: IOError used to be raised; it is now an alias of OSError.
If sys.stdin is used more than once, the second and further use will return no lines, except perhaps for interactive use, or if it has been explicitly reset (e.g. using sys.stdin.seek(0)).
Empty files are opened and immediately closed; the only time their presence in the list of filenames is noticeable at all is when the last file opened is empty.
Lines are returned with any newlines intact, which means that the last line in a file may not have one.
You can control how files are opened by providing an opening hook via the openhook parameter to fileinput.input() or FileInput(). The hook must be a function that takes two arguments, filename and mode, and returns an accordingly opened file-like object. Two useful hooks are already provided by this module.
The following function is the primary interface of this module:
Create an instance of the FileInput class. The instance will be used as global state for the functions of this module, and is also returned to use during iteration. The parameters to this function will be passed along to the constructor of the FileInput class.
The FileInput instance can be used as a context manager in the with statement. In this example, input is closed after the with statement is exited, even if an exception occurs:
Changed in version 3.2: Can be used as a context manager.
Changed in version 3.8: The keyword parameters mode and openhook are now keyword-only.
The following functions use the global state created by fileinput.input(); if there is no active state, RuntimeError is raised.
Return the name of the file currently being read. Before the first line has been read, returns None.
Return the integer “file descriptor” for the current file. When no file is opened (before the first line and between files), returns -1.
Return the cumulative line number of the line that has just been read. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line.
Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file.
Return True if the line just read is the first line of its file, otherwise return False.
Return True if the last line was read from sys.stdin, otherwise return False.
Close the current file so that the next iteration will read the first line from the next file (if any); lines not read from the file will not count towards the cumulative line count. The filename is not changed until after the first line of the next file has been read. Before the first line has been read, this function has no effect; it cannot be used to skip the first file. After the last line of the last file has been read, this function has no effect.
Close the sequence.
The class which implements the sequence behavior provided by the module is available for subclassing as well:
Class FileInput is the implementation; its methods filename(), fileno(), lineno(), filelineno(), isfirstline(), isstdin(), nextfile() and close() correspond to the functions of the same name in the module. In addition it has a readline() method which returns the next input line, and a __getitem__() method which implements the sequence behavior. The sequence must be accessed in strictly sequential order; random access and readline() cannot be mixed.
With mode you can specify which file mode will be passed to open(). It must be one of 'r', 'rU', 'U' and 'rb'.
The openhook, when given, must be a function that takes two arguments, filename and mode, and returns an accordingly opened file-like object. You cannot use inplace and openhook together.
A FileInput instance can be used as a context manager in the with statement. In this example, input is closed after the with statement is exited, even if an exception occurs:
Changed in version 3.2: Can be used as a context manager.
Deprecated since version 3.4: The 'rU' and 'U' modes.
Deprecated since version 3.8: Support for __getitem__() method is deprecated.
Changed in version 3.8: The keyword parameter mode and openhook are now keyword-only.
Optional in-place filtering: if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the backup parameter is given (typically as backup='.<some extension>'), it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read.
The two following opening hooks are provided by this module:
Transparently opens files compressed with gzip and bzip2 (recognized by the extensions '.gz' and '.bz2') using the gzip and bz2 modules. If the filename extension is not '.gz' or '.bz2', the file is opened normally (ie, using open() without any decompression).
Usage example: fi = fileinput.FileInput(openhook=fileinput.hook_compressed)
Returns a hook which opens each file with open(), using the given encoding and errors to read the file.
Usage example: fi =
fileinput.FileInput(openhook=fileinput.hook_encoded("utf-8",
"surrogateescape"))
Changed in version 3.6: Added the optional errors parameter.


Class FileInput is the implementation; its methods filename(), fileno(), lineno(), filelineno(), isfirstline(), isstdin(), nextfile() and close() correspond to the functions of the same name in the module. In addition it has a readline() method which returns the next input line, and a __getitem__() method which implements the sequence behavior. The sequence must be accessed in strictly sequential order; random access and readline() cannot be mixed.
With mode you can specify which file mode will be passed to open(). It must be one of 'r', 'rU', 'U' and 'rb'.
The openhook, when given, must be a function that takes two arguments, filename and mode, and returns an accordingly opened file-like object. You cannot use inplace and openhook together.
A FileInput instance can be used as a context manager in the with statement. In this example, input is closed after the with statement is exited, even if an exception occurs:
Changed in version 3.2: Can be used as a context manager.
Deprecated since version 3.4: The 'rU' and 'U' modes.
Deprecated since version 3.8: Support for __getitem__() method is deprecated.
Changed in version 3.8: The keyword parameter mode and openhook are now keyword-only.


Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file.


Return the name of the file currently being read. Before the first line has been read, returns None.


Return the integer “file descriptor” for the current file. When no file is opened (before the first line and between files), returns -1.


Transparently opens files compressed with gzip and bzip2 (recognized by the extensions '.gz' and '.bz2') using the gzip and bz2 modules. If the filename extension is not '.gz' or '.bz2', the file is opened normally (ie, using open() without any decompression).
Usage example: fi = fileinput.FileInput(openhook=fileinput.hook_compressed)


Returns a hook which opens each file with open(), using the given encoding and errors to read the file.
Usage example: fi =
fileinput.FileInput(openhook=fileinput.hook_encoded("utf-8",
"surrogateescape"))
Changed in version 3.6: Added the optional errors parameter.


Create an instance of the FileInput class. The instance will be used as global state for the functions of this module, and is also returned to use during iteration. The parameters to this function will be passed along to the constructor of the FileInput class.
The FileInput instance can be used as a context manager in the with statement. In this example, input is closed after the with statement is exited, even if an exception occurs:
Changed in version 3.2: Can be used as a context manager.
Changed in version 3.8: The keyword parameters mode and openhook are now keyword-only.


Return True if the line just read is the first line of its file, otherwise return False.


Return True if the last line was read from sys.stdin, otherwise return False.


Return the cumulative line number of the line that has just been read. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line.


Close the current file so that the next iteration will read the first line from the next file (if any); lines not read from the file will not count towards the cumulative line count. The filename is not changed until after the first line of the next file has been read. Before the first line has been read, this function has no effect; it cannot be used to skip the first file. After the last line of the last file has been read, this function has no effect.


Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.


Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.
See itertools.filterfalse() for the complementary function that returns elements of iterable for which function returns false.


Return a floating point number constructed from a number or string x.
If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity. More precisely, the input must conform to the following grammar after leading and trailing whitespace characters are removed:
Here floatnumber is the form of a Python floating-point literal, described in Floating point literals. Case is not significant, so, for example, “inf”, “Inf”, “INFINITY” and “iNfINity” are all acceptable spellings for positive infinity.
Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python’s floating point precision) is returned. If the argument is outside the range of a Python float, an OverflowError will be raised.
For a general Python object x, float(x) delegates to x.__float__(). If __float__() is not defined then it falls back to __index__().
If no argument is given, 0.0 is returned.
Examples:
The float type is described in Numeric Types — int, float, complex.
Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.
Changed in version 3.7: x is now a positional-only parameter.
Changed in version 3.8: Falls back to __index__() if __float__() is not defined.


Return a pair of integers whose ratio is exactly equal to the original float and with a positive denominator. Raises OverflowError on infinities and a ValueError on NaNs.


Class method to return the float represented by a hexadecimal string s. The string s may have leading and trailing whitespace.


Return a representation of a floating-point number as a hexadecimal string. For finite floating-point numbers, this representation will always include a leading 0x and a trailing p and exponent.


Return True if the float instance is finite with integral value, and False otherwise:


Source code: Lib/fnmatch.py
This module provides support for Unix shell-style wildcards, which are not the same as regular expressions (which are documented in the re module). The special characters used in shell-style wildcards are:
Pattern
Meaning
*
matches everything
?
matches any single character
[seq]
matches any character in seq
[!seq]
matches any character not in seq
For a literal match, wrap the meta-characters in brackets. For example, '[?]' matches the character '?'.
Note that the filename separator ('/' on Unix) is not special to this module. See module glob for pathname expansion (glob uses filter() to match pathname segments). Similarly, filenames starting with a period are not special for this module, and are matched by the * and ? patterns.
Test whether the filename string matches the pattern string, returning True or False. Both parameters are case-normalized using os.path.normcase(). fnmatchcase() can be used to perform a case-sensitive comparison, regardless of whether that’s standard for the operating system.
This example will print all file names in the current directory with the extension .txt:
Test whether filename matches pattern, returning True or False; the comparison is case-sensitive and does not apply os.path.normcase().
Construct a list from those elements of the iterable names that match pattern. It is the same as [n for n in names if fnmatch(n, pattern)], but implemented more efficiently.
Return the shell-style pattern converted to a regular expression for using with re.match().
Example:
See also
Unix shell-style path expansion.


Construct a list from those elements of the iterable names that match pattern. It is the same as [n for n in names if fnmatch(n, pattern)], but implemented more efficiently.


Test whether the filename string matches the pattern string, returning True or False. Both parameters are case-normalized using os.path.normcase(). fnmatchcase() can be used to perform a case-sensitive comparison, regardless of whether that’s standard for the operating system.
This example will print all file names in the current directory with the extension .txt:


Test whether filename matches pattern, returning True or False; the comparison is case-sensitive and does not apply os.path.normcase().


Return the shell-style pattern converted to a regular expression for using with re.match().
Example:


Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.
The default format_spec is an empty string which usually gives the same effect as calling str(value).
A call to format(value, format_spec) is translated to type(value).__format__(value, format_spec) which bypasses the instance dictionary when searching for the value’s __format__() method. A TypeError exception is raised if the method search reaches object and the format_spec is non-empty, or if either the format_spec or the return value are not strings.
Changed in version 3.4: object().__format__(format_spec) raises TypeError if format_spec is not an empty string.


Source code: Lib/fractions.py
The fractions module provides support for rational number arithmetic.
A Fraction instance can be constructed from a pair of integers, from another rational number, or from a string.
The first version requires that numerator and denominator are instances of numbers.Rational and returns a new Fraction instance with value numerator/denominator. If denominator is 0, it raises a ZeroDivisionError. The second version requires that other_fraction is an instance of numbers.Rational and returns a Fraction instance with the same value. The next two versions accept either a float or a decimal.Decimal instance, and return a Fraction instance with exactly the same value. Note that due to the usual issues with binary floating-point (see Floating Point Arithmetic: Issues and Limitations), the argument to Fraction(1.1) is not exactly equal to 11/10, and so Fraction(1.1) does not return Fraction(11, 10) as one might expect. (But see the documentation for the limit_denominator() method below.) The last version of the constructor expects a string or unicode instance. The usual form for this instance is:
where the optional sign may be either ‘+’ or ‘-‘ and numerator and denominator (if present) are strings of decimal digits. In addition, any string that represents a finite value and is accepted by the float constructor is also accepted by the Fraction constructor. In either form the input string may also have leading and/or trailing whitespace. Here are some examples:
The Fraction class inherits from the abstract base class numbers.Rational, and implements all of the methods and operations from that class. Fraction instances are hashable, and should be treated as immutable. In addition, Fraction has the following properties and methods:
Changed in version 3.2: The Fraction constructor now accepts float and decimal.Decimal instances.
Changed in version 3.9: The math.gcd() function is now used to normalize the numerator and denominator. math.gcd() always return a int type. Previously, the GCD type depended on numerator and denominator.
Numerator of the Fraction in lowest term.
Denominator of the Fraction in lowest term.
Return a tuple of two integers, whose ratio is equal to the Fraction and with a positive denominator.
New in version 3.8.
This class method constructs a Fraction representing the exact value of flt, which must be a float. Beware that Fraction.from_float(0.3) is not the same value as Fraction(3, 10).
Note
From Python 3.2 onwards, you can also construct a Fraction instance directly from a float.
This class method constructs a Fraction representing the exact value of dec, which must be a decimal.Decimal instance.
Note
From Python 3.2 onwards, you can also construct a Fraction instance directly from a decimal.Decimal instance.
Finds and returns the closest Fraction to self that has denominator at most max_denominator. This method is useful for finding rational approximations to a given floating-point number:
or for recovering a rational number that’s represented as a float:
Returns the greatest int <= self. This method can also be accessed through the math.floor() function:
Returns the least int >= self. This method can also be accessed through the math.ceil() function.
The first version returns the nearest int to self, rounding half to even. The second version rounds self to the nearest multiple of Fraction(1, 10**ndigits) (logically, if ndigits is negative), again rounding half toward even. This method can also be accessed through the round() function.
See also
The abstract base classes making up the numeric tower.