A decorator for importlib.abc.Loader.load_module() to set the __loader__ attribute on the returned module. If the attribute is already set the decorator does nothing. It is assumed that the first positional argument to the wrapped method (i.e. self) is what __loader__ should be set to.
Changed in version 3.4: Set __loader__ if set to None, as if the attribute does not exist.
Deprecated since version 3.4: The import machinery takes care of this automatically.


A decorator for importlib.abc.Loader.load_module() to set the __package__ attribute on the returned module. If __package__ is set and has a value other than None it will not be changed.
Deprecated since version 3.4: The import machinery takes care of this automatically.


Given the path to a PEP 3147 file name, return the associated source code file path. For example, if path is /foo/bar/__pycache__/baz.cpython-32.pyc the returned path would be /foo/bar/baz.py. path need not exist, however if it does not conform to PEP 3147 or PEP 488 format, a ValueError is raised. If sys.implementation.cache_tag is not defined, NotImplementedError is raised.
New in version 3.4.
Changed in version 3.6: Accepts a path-like object.


Return the hash of source_bytes as bytes. A hash-based .pyc file embeds the source_hash() of the corresponding source file’s contents in its header.
New in version 3.7.


A factory function for creating a ModuleSpec instance based on the path to a file. Missing information will be filled in on the spec by making use of loader APIs and by the implication that the module will be file-based.
New in version 3.4.
Changed in version 3.6: Accepts a path-like object.


A factory function for creating a ModuleSpec instance based on a loader. The parameters have the same meaning as they do for ModuleSpec. The function uses available loader APIs, such as InspectLoader.is_package(), to fill in any missing information on the spec.
New in version 3.4.


An implementation of the built-in __import__() function.
Note
Programmatic importing of modules should use import_module() instead of this function.


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 syntax errors related to incorrect indentation. This is a subclass of SyntaxError.


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.)


If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:
If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.
Raises an auditing event builtins.input with argument prompt before reading input
Raises an auditing event builtins.input/result with the result after successfully reading input.


Source code: Lib/inspect.py
The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.
There are four main kinds of services provided by this module: type checking, getting source code, inspecting classes and functions, and examining the interpreter stack.
The getmembers() function retrieves the members of an object such as a class or module. The functions whose names begin with “is” are mainly provided as convenient choices for the second argument to getmembers(). They also help you determine when you can expect to find the following special attributes:
Type
Attribute
Description
module
__doc__
documentation string
__file__
filename (missing for built-in modules)
class
__doc__
documentation string
__name__
name with which this class was defined
__qualname__
qualified name
__module__
name of module in which this class was defined
method
__doc__
documentation string
__name__
name with which this method was defined
__qualname__
qualified name
__func__
function object containing implementation of method
__self__
instance to which this method is bound, or None
__module__
name of module in which this method was defined
function
__doc__
documentation string
__name__
name with which this function was defined
__qualname__
qualified name
__code__
code object containing compiled function bytecode
__defaults__
tuple of any default values for positional or keyword parameters
__kwdefaults__
mapping of any default values for keyword-only parameters
__globals__
global namespace in which this function was defined
__annotations__
mapping of parameters names to annotations; "return" key is reserved for return annotations.
__module__
name of module in which this function was defined
traceback
tb_frame
frame object at this level
tb_lasti
index of last attempted instruction in bytecode
tb_lineno
current line number in Python source code
tb_next
next inner traceback object (called by this level)
frame
f_back
next outer frame object (this frame’s caller)
f_builtins
builtins namespace seen by this frame
f_code
code object being executed in this frame
f_globals
global namespace seen by this frame
f_lasti
index of last attempted instruction in bytecode
f_lineno
current line number in Python source code
f_locals
local namespace seen by this frame
f_trace
tracing function for this frame, or None
code
co_argcount
number of arguments (not including keyword only arguments, * or ** args)
co_code
string of raw compiled bytecode
co_cellvars
tuple of names of cell variables (referenced by containing scopes)
co_consts
tuple of constants used in the bytecode
co_filename
name of file in which this code object was created
co_firstlineno
number of first line in Python source code
co_flags
bitmap of CO_* flags, read more here
co_lnotab
encoded mapping of line numbers to bytecode indices
co_freevars
tuple of names of free variables (referenced via a function’s closure)
co_posonlyargcount
number of positional only arguments
co_kwonlyargcount
number of keyword only arguments (not including ** arg)
co_name
name with which this code object was defined
co_names
tuple of names of local variables
co_nlocals
number of local variables
co_stacksize
virtual machine stack space required
co_varnames
tuple of names of arguments and local variables
generator
__name__
name
__qualname__
qualified name
gi_frame
frame
gi_running
is the generator running?
gi_code
code
gi_yieldfrom
object being iterated by yield from, or None
coroutine
__name__
name
__qualname__
qualified name
cr_await
object being awaited on, or None
cr_frame
frame
cr_running
is the coroutine running?
cr_code
code
cr_origin
where coroutine was created, or None. See sys.set_coroutine_origin_tracking_depth()
builtin
__doc__
documentation string
__name__
original name of this function or method
__qualname__
qualified name
__self__
instance to which a method is bound, or None
Changed in version 3.5: Add __qualname__ and gi_yieldfrom attributes to generators.
The __name__ attribute of generators is now set from the function name, instead of the code name, and it can now be modified.
Changed in version 3.7: Add cr_origin attribute to coroutines.
Return all the members of an object in a list of (name, value) pairs sorted by name. If the optional predicate argument—which will be called with the value object of each member—is supplied, only members for which the predicate returns a true value are included.
Note
getmembers() will only return class attributes defined in the metaclass when the argument is a class and those attributes have been listed in the metaclass’ custom __dir__().
Return the name of the module named by the file path, without including the names of enclosing packages. The file extension is checked against all of the entries in importlib.machinery.all_suffixes(). If it matches, the final path component is returned with the extension removed. Otherwise, None is returned.
Note that this function only returns a meaningful name for actual Python modules - paths that potentially refer to Python packages will still return None.
Changed in version 3.3: The function is based directly on importlib.
Return True if the object is a module.
Return True if the object is a class, whether built-in or created in Python code.
Return True if the object is a bound method written in Python.
Return True if the object is a Python function, which includes functions created by a lambda expression.
Return True if the object is a Python generator function.
Changed in version 3.8: Functions wrapped in functools.partial() now return True if the wrapped function is a Python generator function.
Return True if the object is a generator.
Return True if the object is a coroutine function (a function defined with an async def syntax).
New in version 3.5.
Changed in version 3.8: Functions wrapped in functools.partial() now return True if the wrapped function is a coroutine function.
Return True if the object is a coroutine created by an async def function.
New in version 3.5.
Return True if the object can be used in await expression.
Can also be used to distinguish generator-based coroutines from regular generators:
New in version 3.5.
Return True if the object is an asynchronous generator function, for example:
New in version 3.6.
Changed in version 3.8: Functions wrapped in functools.partial() now return True if the wrapped function is a asynchronous generator function.
Return True if the object is an asynchronous generator iterator created by an asynchronous generator function.
New in version 3.6.
Return True if the object is a traceback.
Return True if the object is a frame.
Return True if the object is a code.
Return True if the object is a built-in function or a bound built-in method.
Return True if the object is a user-defined or built-in function or method.
Return True if the object is an abstract base class.
Return True if the object is a method descriptor, but not if ismethod(), isclass(), isfunction() or isbuiltin() are true.
This, for example, is true of int.__add__. An object passing this test has a __get__() method but not a __set__() method, but beyond that the set of attributes varies. A __name__ attribute is usually sensible, and __doc__ often is.
Methods implemented via descriptors that also pass one of the other tests return False from the ismethoddescriptor() test, simply because the other tests promise more – you can, e.g., count on having the __func__ attribute (etc) when an object passes ismethod().
Return True if the object is a data descriptor.
Data descriptors have a __set__ or a __delete__ method. Examples are properties (defined in Python), getsets, and members. The latter two are defined in C and there are more specific tests available for those types, which is robust across Python implementations. Typically, data descriptors will also have __name__ and __doc__ attributes (properties, getsets, and members have both of these attributes), but this is not guaranteed.
Return True if the object is a getset descriptor.
CPython implementation detail: getsets are attributes defined in extension modules via PyGetSetDef structures. For Python implementations without such types, this method will always return False.
Return True if the object is a member descriptor.
CPython implementation detail: Member descriptors are attributes defined in extension modules via PyMemberDef structures. For Python implementations without such types, this method will always return False.
Get the documentation string for an object, cleaned up with cleandoc(). If the documentation string for an object is not provided and the object is a class, a method, a property or a descriptor, retrieve the documentation string from the inheritance hierarchy.
Changed in version 3.5: Documentation strings are now inherited if not overridden.
Return in a single string any lines of comments immediately preceding the object’s source code (for a class, function, or method), or at the top of the Python source file (if the object is a module). If the object’s source code is unavailable, return None. This could happen if the object has been defined in C or the interactive shell.
Return the name of the (text or binary) file in which an object was defined. This will fail with a TypeError if the object is a built-in module, class, or function.
Try to guess which module an object was defined in.
Return the name of the Python source file in which an object was defined. This will fail with a TypeError if the object is a built-in module, class, or function.
Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An OSError is raised if the source code cannot be retrieved.
Changed in version 3.3: OSError is raised instead of IOError, now an alias of the former.
Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An OSError is raised if the source code cannot be retrieved.
Changed in version 3.3: OSError is raised instead of IOError, now an alias of the former.
Clean up indentation from docstrings that are indented to line up with blocks of code.
All leading whitespace is removed from the first line. Any leading whitespace that can be uniformly removed from the second line onwards is removed. Empty lines at the beginning and end are subsequently removed. Also, all tabs are expanded to spaces.
New in version 3.3.
The Signature object represents the call signature of a callable object and its return annotation. To retrieve a Signature object, use the signature() function.
Return a Signature object for the given callable:
Accepts a wide range of Python callables, from plain functions and classes to functools.partial() objects.
Raises ValueError if no signature can be provided, and TypeError if that type of object is not supported.
A slash(/) in the signature of a function denotes that the parameters prior to it are positional-only. For more info, see the FAQ entry on positional-only parameters.
New in version 3.5: follow_wrapped parameter. Pass False to get a signature of callable specifically (callable.__wrapped__ will not be used to unwrap decorated callables.)
Note
Some callables may not be introspectable in certain implementations of Python. For example, in CPython, some built-in functions defined in C provide no metadata about their arguments.
A Signature object represents the call signature of a function and its return annotation. For each parameter accepted by the function it stores a Parameter object in its parameters collection.
The optional parameters argument is a sequence of Parameter objects, which is validated to check that there are no parameters with duplicate names, and that the parameters are in the right order, i.e. positional-only first, then positional-or-keyword, and that parameters with defaults follow parameters without defaults.
The optional return_annotation argument, can be an arbitrary Python object, is the “return” annotation of the callable.
Signature objects are immutable. Use Signature.replace() to make a modified copy.
Changed in version 3.5: Signature objects are picklable and hashable.
A special class-level marker to specify absence of a return annotation.
An ordered mapping of parameters’ names to the corresponding Parameter objects. Parameters appear in strict definition order, including keyword-only parameters.
Changed in version 3.7: Python only explicitly guaranteed that it preserved the declaration order of keyword-only parameters as of version 3.7, although in practice this order had always been preserved in Python 3.
The “return” annotation for the callable. If the callable has no “return” annotation, this attribute is set to Signature.empty.
Create a mapping from positional and keyword arguments to parameters. Returns BoundArguments if *args and **kwargs match the signature, or raises a TypeError.
Works the same way as Signature.bind(), but allows the omission of some required arguments (mimics functools.partial() behavior.) Returns BoundArguments, or raises a TypeError if the passed arguments do not match the signature.
Create a new Signature instance based on the instance replace was invoked on. It is possible to pass different parameters and/or return_annotation to override the corresponding properties of the base signature. To remove return_annotation from the copied Signature, pass in Signature.empty.
Return a Signature (or its subclass) object for a given callable obj. Pass follow_wrapped=False to get a signature of obj without unwrapping its __wrapped__ chain.
This method simplifies subclassing of Signature:
New in version 3.5.
Parameter objects are immutable. Instead of modifying a Parameter object, you can use Parameter.replace() to create a modified copy.
Changed in version 3.5: Parameter objects are picklable and hashable.
A special class-level marker to specify absence of default values and annotations.
The name of the parameter as a string. The name must be a valid Python identifier.
CPython implementation detail: CPython generates implicit parameter names of the form .0 on the code objects used to implement comprehensions and generator expressions.
Changed in version 3.6: These parameter names are exposed by this module as names like implicit0.
The default value for the parameter. If the parameter has no default value, this attribute is set to Parameter.empty.
The annotation for the parameter. If the parameter has no annotation, this attribute is set to Parameter.empty.
Describes how argument values are bound to the parameter. Possible values (accessible via Parameter, like Parameter.KEYWORD_ONLY):
Name
Meaning
POSITIONAL_ONLY
Value must be supplied as a positional argument. Positional only parameters are those which appear before a / entry (if present) in a Python function definition.
POSITIONAL_OR_KEYWORD
Value may be supplied as either a keyword or positional argument (this is the standard binding behaviour for functions implemented in Python.)
VAR_POSITIONAL
A tuple of positional arguments that aren’t bound to any other parameter. This corresponds to a *args parameter in a Python function definition.
KEYWORD_ONLY
Value must be supplied as a keyword argument. Keyword only parameters are those which appear after a * or *args entry in a Python function definition.
VAR_KEYWORD
A dict of keyword arguments that aren’t bound to any other parameter. This corresponds to a **kwargs parameter in a Python function definition.
Example: print all keyword-only arguments without default values:
Describes a enum value of Parameter.kind.
New in version 3.8.
Example: print all descriptions of arguments:
Create a new Parameter instance based on the instance replaced was invoked on. To override a Parameter attribute, pass the corresponding argument. To remove a default value or/and an annotation from a Parameter, pass Parameter.empty.
Changed in version 3.4: In Python 3.3 Parameter objects were allowed to have name set to None if their kind was set to POSITIONAL_ONLY. This is no longer permitted.
Result of a Signature.bind() or Signature.bind_partial() call. Holds the mapping of arguments to the function’s parameters.
A mutable mapping of parameters’ names to arguments’ values. Contains only explicitly bound arguments. Changes in arguments will reflect in args and kwargs.
Should be used in conjunction with Signature.parameters for any argument processing purposes.
Note
Arguments for which Signature.bind() or Signature.bind_partial() relied on a default value are skipped. However, if needed, use BoundArguments.apply_defaults() to add them.
Changed in version 3.9: arguments is now of type dict. Formerly, it was of type collections.OrderedDict.
A tuple of positional arguments values. Dynamically computed from the arguments attribute.
A dict of keyword arguments values. Dynamically computed from the arguments attribute.
A reference to the parent Signature object.
Set default values for missing arguments.
For variable-positional arguments (*args) the default is an empty tuple.
For variable-keyword arguments (**kwargs) the default is an empty dict.
New in version 3.5.
The args and kwargs properties can be used to invoke functions:
See also
The detailed specification, implementation details and examples.
Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. Each entry is a 2-tuple containing a class and a tuple of its base classes. If the unique argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times.
Get the names and default values of a Python function’s parameters. A named tuple ArgSpec(args, varargs, keywords, defaults) is returned. args is a list of the parameter names. varargs and keywords are the names of the * and ** parameters or None. defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.
Deprecated since version 3.0: Use getfullargspec() for an updated API that is usually a drop-in replacement, but also correctly handles function annotations and keyword-only parameters.
Alternatively, use signature() and Signature Object, which provide a more structured introspection API for callables.
Get the names and default values of a Python function’s parameters. A named tuple is returned:
FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
annotations)
args is a list of the positional parameter names. varargs is the name of the * parameter or None if arbitrary positional arguments are not accepted. varkw is the name of the ** parameter or None if arbitrary keyword arguments are not accepted. defaults is an n-tuple of default argument values corresponding to the last n positional parameters, or None if there are no such defaults defined. kwonlyargs is a list of keyword-only parameter names in declaration order. kwonlydefaults is a dictionary mapping parameter names from kwonlyargs to the default values used if no argument is supplied. annotations is a dictionary mapping parameter names to annotations. The special key "return" is used to report the function return value annotation (if any).
Note that signature() and Signature Object provide the recommended API for callable introspection, and support additional behaviours (like positional-only arguments) that are sometimes encountered in extension module APIs. This function is retained primarily for use in code that needs to maintain compatibility with the Python 2 inspect module API.
Changed in version 3.4: This function is now based on signature(), but still ignores __wrapped__ attributes and includes the already bound first parameter in the signature output for bound methods.
Changed in version 3.6: This method was previously documented as deprecated in favour of signature() in Python 3.5, but that decision has been reversed in order to restore a clearly supported standard interface for single-source Python 2/3 code migrating away from the legacy getargspec() API.
Changed in version 3.7: Python only explicitly guaranteed that it preserved the declaration order of keyword-only parameters as of version 3.7, although in practice this order had always been preserved in Python 3.
Get information about arguments passed into a particular frame. A named tuple ArgInfo(args, varargs, keywords, locals) is returned. args is a list of the argument names. varargs and keywords are the names of the * and ** arguments or None. locals is the locals dictionary of the given frame.
Note
This function was inadvertently marked as deprecated in Python 3.5.
Format a pretty argument spec from the values returned by getfullargspec().
The first seven arguments are (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations).
The other six arguments are functions that are called to turn argument names, * argument name, ** argument name, default values, return annotation and individual annotations into strings, respectively.
For example:
Deprecated since version 3.5: Use signature() and Signature Object, which provide a better introspecting API for callables.
Format a pretty argument spec from the four values returned by getargvalues(). The format* arguments are the corresponding optional formatting functions that are called to turn names and values into strings.
Note
This function was inadvertently marked as deprecated in Python 3.5.
Return a tuple of class cls’s base classes, including cls, in method resolution order. No class appears more than once in this tuple. Note that the method resolution order depends on cls’s type. Unless a very peculiar user-defined metatype is in use, cls will be the first element of the tuple.
Bind the args and kwds to the argument names of the Python function or method func, as if it was called with them. For bound methods, bind also the first argument (typically named self) to the associated instance. A dict is returned, mapping the argument names (including the names of the * and ** arguments, if any) to their values from args and kwds. In case of invoking func incorrectly, i.e. whenever func(*args, **kwds) would raise an exception because of incompatible signature, an exception of the same type and the same or similar message is raised. For example:
New in version 3.2.
Deprecated since version 3.5: Use Signature.bind() and Signature.bind_partial() instead.
Get the mapping of external name references in a Python function or method func to their current values. A named tuple ClosureVars(nonlocals, globals, builtins, unbound) is returned. nonlocals maps referenced names to lexical closure variables, globals to the function’s module globals and builtins to the builtins visible from the function body. unbound is the set of names referenced in the function that could not be resolved at all given the current module globals and builtins.
TypeError is raised if func is not a Python function or method.
New in version 3.3.
Get the object wrapped by func. It follows the chain of __wrapped__ attributes returning the last object in the chain.
stop is an optional callback accepting an object in the wrapper chain as its sole argument that allows the unwrapping to be terminated early if the callback returns a true value. If the callback never returns a true value, the last object in the chain is returned as usual. For example, signature() uses this to stop unwrapping if any object in the chain has a __signature__ attribute defined.
ValueError is raised if a cycle is encountered.
New in version 3.4.
When the following functions return “frame records,” each record is a named tuple FrameInfo(frame, filename, lineno, function, code_context, index). The tuple contains the frame object, the filename, the line number of the current line, the function name, a list of lines of context from the source code, and the index of the current line within that list.
Changed in version 3.5: Return a named tuple instead of a tuple.
Note
Keeping references to frame objects, as found in the first element of the frame records these functions return, can cause your program to create reference cycles. Once a reference cycle has been created, the lifespan of all objects which can be accessed from the objects which form the cycle can become much longer even if Python’s optional cycle detector is enabled. If such cycles must be created, it is important to ensure they are explicitly broken to avoid the delayed destruction of objects and increased memory consumption which occurs.
Though the cycle detector will catch these, destruction of the frames (and local variables) can be made deterministic by removing the cycle in a finally clause. This is also important if the cycle detector was disabled when Python was compiled or using gc.disable(). For example:
If you want to keep the frame around (for example to print a traceback later), you can also break reference cycles by using the frame.clear() method.
The optional context argument supported by most of these functions specifies the number of lines of context to return, which are centered around the current line.
Get information about a frame or traceback object. A named tuple Traceback(filename, lineno, function, code_context, index) is returned.
Get a list of frame records for a frame and all outer frames. These frames represent the calls that lead to the creation of frame. The first entry in the returned list represents frame; the last entry represents the outermost call on frame’s stack.
Changed in version 3.5: A list of named tuples FrameInfo(frame, filename, lineno, function, code_context, index) is returned.
Get a list of frame records for a traceback’s frame and all inner frames. These frames represent calls made as a consequence of frame. The first entry in the list represents traceback; the last entry represents where the exception was raised.
Changed in version 3.5: A list of named tuples FrameInfo(frame, filename, lineno, function, code_context, index) is returned.
Return the frame object for the caller’s stack frame.
CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None.
Return a list of frame records for the caller’s stack. The first entry in the returned list represents the caller; the last entry represents the outermost call on the stack.
Changed in version 3.5: A list of named tuples FrameInfo(frame, filename, lineno, function, code_context, index) is returned.
Return a list of frame records for the stack between the current frame and the frame in which an exception currently being handled was raised in. The first entry in the list represents the caller; the last entry represents where the exception was raised.
Changed in version 3.5: A list of named tuples FrameInfo(frame, filename, lineno, function, code_context, index) is returned.
Both getattr() and hasattr() can trigger code execution when fetching or checking for the existence of attributes. Descriptors, like properties, will be invoked and __getattr__() and __getattribute__() may be called.
For cases where you want passive introspection, like documentation tools, this can be inconvenient. getattr_static() has the same signature as getattr() but avoids executing code when it fetches attributes.
Retrieve attributes without triggering dynamic lookup via the descriptor protocol, __getattr__() or __getattribute__().
Note: this function may not be able to retrieve all attributes that getattr can fetch (like dynamically created attributes) and may find attributes that getattr can’t (like descriptors that raise AttributeError). It can also return descriptors objects instead of instance members.
If the instance __dict__ is shadowed by another member (for example a property) then this function will be unable to find instance members.
New in version 3.2.
getattr_static() does not resolve descriptors, for example slot descriptors or getset descriptors on objects implemented in C. The descriptor object is returned instead of the underlying attribute.
You can handle these with code like the following. Note that for arbitrary getset descriptors invoking these may trigger code execution:
When implementing coroutine schedulers and for other advanced uses of generators, it is useful to determine whether a generator is currently executing, is waiting to start or resume or execution, or has already terminated. getgeneratorstate() allows the current state of a generator to be determined easily.
Get current state of a generator-iterator.
New in version 3.2.
Get current state of a coroutine object. The function is intended to be used with coroutine objects created by async def functions, but will accept any coroutine-like object that has cr_running and cr_frame attributes.
New in version 3.5.
The current internal state of the generator can also be queried. This is mostly useful for testing purposes, to ensure that internal state is being updated as expected:
Get the mapping of live local variables in generator to their current values. A dictionary is returned that maps from variable names to values. This is the equivalent of calling locals() in the body of the generator, and all the same caveats apply.
If generator is a generator with no currently associated frame, then an empty dictionary is returned. TypeError is raised if generator is not a Python generator object.
CPython implementation detail: This function relies on the generator exposing a Python stack frame for introspection, which isn’t guaranteed to be the case in all implementations of Python. In such cases, this function will always return an empty dictionary.
New in version 3.3.
This function is analogous to getgeneratorlocals(), but works for coroutine objects created by async def functions.
New in version 3.5.
Python code objects have a co_flags attribute, which is a bitmap of the following flags:
The code object is optimized, using fast locals.
If set, a new dict will be created for the frame’s f_locals when the code object is executed.
The code object has a variable positional parameter (*args-like).
The code object has a variable keyword parameter (**kwargs-like).
The flag is set when the code object is a nested function.
The flag is set when the code object is a generator function, i.e. a generator object is returned when the code object is executed.
The flag is set if there are no free or cell variables.
The flag is set when the code object is a coroutine function. When the code object is executed it returns a coroutine object. See PEP 492 for more details.
New in version 3.5.
The flag is used to transform generators into generator-based coroutines. Generator objects with this flag can be used in await expression, and can yield from coroutine objects. See PEP 492 for more details.
New in version 3.5.
The flag is set when the code object is an asynchronous generator function. When the code object is executed it returns an asynchronous generator object. See PEP 525 for more details.
New in version 3.6.
Note
The flags are specific to CPython, and may not be defined in other Python implementations. Furthermore, the flags are an implementation detail, and can be removed or deprecated in future Python releases. It’s recommended to use public APIs from the inspect module for any introspection needs.
The inspect module also provides a basic introspection capability from the command line.
By default, accepts the name of a module and prints the source of that module. A class or function within the module can be printed instead by appended a colon and the qualified name of the target object.
Print information about the specified object rather than the source code


Result of a Signature.bind() or Signature.bind_partial() call. Holds the mapping of arguments to the function’s parameters.
A mutable mapping of parameters’ names to arguments’ values. Contains only explicitly bound arguments. Changes in arguments will reflect in args and kwargs.
Should be used in conjunction with Signature.parameters for any argument processing purposes.
Note
Arguments for which Signature.bind() or Signature.bind_partial() relied on a default value are skipped. However, if needed, use BoundArguments.apply_defaults() to add them.
Changed in version 3.9: arguments is now of type dict. Formerly, it was of type collections.OrderedDict.
A tuple of positional arguments values. Dynamically computed from the arguments attribute.
A dict of keyword arguments values. Dynamically computed from the arguments attribute.
A reference to the parent Signature object.
Set default values for missing arguments.
For variable-positional arguments (*args) the default is an empty tuple.
For variable-keyword arguments (**kwargs) the default is an empty dict.
New in version 3.5.
The args and kwargs properties can be used to invoke functions:


Set default values for missing arguments.
For variable-positional arguments (*args) the default is an empty tuple.
For variable-keyword arguments (**kwargs) the default is an empty dict.
New in version 3.5.


A tuple of positional arguments values. Dynamically computed from the arguments attribute.


A mutable mapping of parameters’ names to arguments’ values. Contains only explicitly bound arguments. Changes in arguments will reflect in args and kwargs.
Should be used in conjunction with Signature.parameters for any argument processing purposes.
Note
Arguments for which Signature.bind() or Signature.bind_partial() relied on a default value are skipped. However, if needed, use BoundArguments.apply_defaults() to add them.
Changed in version 3.9: arguments is now of type dict. Formerly, it was of type collections.OrderedDict.


A dict of keyword arguments values. Dynamically computed from the arguments attribute.


A reference to the parent Signature object.


Clean up indentation from docstrings that are indented to line up with blocks of code.
All leading whitespace is removed from the first line. Any leading whitespace that can be uniformly removed from the second line onwards is removed. Empty lines at the beginning and end are subsequently removed. Also, all tabs are expanded to spaces.


The flag is set when the code object is an asynchronous generator function. When the code object is executed it returns an asynchronous generator object. See PEP 525 for more details.
New in version 3.6.


The flag is set when the code object is a coroutine function. When the code object is executed it returns a coroutine object. See PEP 492 for more details.
New in version 3.5.


The flag is set when the code object is a generator function, i.e. a generator object is returned when the code object is executed.


The flag is used to transform generators into generator-based coroutines. Generator objects with this flag can be used in await expression, and can yield from coroutine objects. See PEP 492 for more details.
New in version 3.5.


The flag is set when the code object is a nested function.


If set, a new dict will be created for the frame’s f_locals when the code object is executed.


The flag is set if there are no free or cell variables.


The code object is optimized, using fast locals.


The code object has a variable positional parameter (*args-like).


The code object has a variable keyword parameter (**kwargs-like).


Return the frame object for the caller’s stack frame.
CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None.


Format a pretty argument spec from the values returned by getfullargspec().
The first seven arguments are (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations).
The other six arguments are functions that are called to turn argument names, * argument name, ** argument name, default values, return annotation and individual annotations into strings, respectively.
For example:
Deprecated since version 3.5: Use signature() and Signature Object, which provide a better introspecting API for callables.


Format a pretty argument spec from the four values returned by getargvalues(). The format* arguments are the corresponding optional formatting functions that are called to turn names and values into strings.
Note
This function was inadvertently marked as deprecated in Python 3.5.


Get the names and default values of a Python function’s parameters. A named tuple ArgSpec(args, varargs, keywords, defaults) is returned. args is a list of the parameter names. varargs and keywords are the names of the * and ** parameters or None. defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.
Deprecated since version 3.0: Use getfullargspec() for an updated API that is usually a drop-in replacement, but also correctly handles function annotations and keyword-only parameters.
Alternatively, use signature() and Signature Object, which provide a more structured introspection API for callables.


Get information about arguments passed into a particular frame. A named tuple ArgInfo(args, varargs, keywords, locals) is returned. args is a list of the argument names. varargs and keywords are the names of the * and ** arguments or None. locals is the locals dictionary of the given frame.
Note
This function was inadvertently marked as deprecated in Python 3.5.


Retrieve attributes without triggering dynamic lookup via the descriptor protocol, __getattr__() or __getattribute__().
Note: this function may not be able to retrieve all attributes that getattr can fetch (like dynamically created attributes) and may find attributes that getattr can’t (like descriptors that raise AttributeError). It can also return descriptors objects instead of instance members.
If the instance __dict__ is shadowed by another member (for example a property) then this function will be unable to find instance members.
New in version 3.2.


Bind the args and kwds to the argument names of the Python function or method func, as if it was called with them. For bound methods, bind also the first argument (typically named self) to the associated instance. A dict is returned, mapping the argument names (including the names of the * and ** arguments, if any) to their values from args and kwds. In case of invoking func incorrectly, i.e. whenever func(*args, **kwds) would raise an exception because of incompatible signature, an exception of the same type and the same or similar message is raised. For example:
New in version 3.2.
Deprecated since version 3.5: Use Signature.bind() and Signature.bind_partial() instead.


Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. Each entry is a 2-tuple containing a class and a tuple of its base classes. If the unique argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times.


Get the mapping of external name references in a Python function or method func to their current values. A named tuple ClosureVars(nonlocals, globals, builtins, unbound) is returned. nonlocals maps referenced names to lexical closure variables, globals to the function’s module globals and builtins to the builtins visible from the function body. unbound is the set of names referenced in the function that could not be resolved at all given the current module globals and builtins.
TypeError is raised if func is not a Python function or method.
New in version 3.3.


Return in a single string any lines of comments immediately preceding the object’s source code (for a class, function, or method), or at the top of the Python source file (if the object is a module). If the object’s source code is unavailable, return None. This could happen if the object has been defined in C or the interactive shell.


This function is analogous to getgeneratorlocals(), but works for coroutine objects created by async def functions.
New in version 3.5.


Get current state of a coroutine object. The function is intended to be used with coroutine objects created by async def functions, but will accept any coroutine-like object that has cr_running and cr_frame attributes.
New in version 3.5.


Get the documentation string for an object, cleaned up with cleandoc(). If the documentation string for an object is not provided and the object is a class, a method, a property or a descriptor, retrieve the documentation string from the inheritance hierarchy.
Changed in version 3.5: Documentation strings are now inherited if not overridden.


Return the name of the (text or binary) file in which an object was defined. This will fail with a TypeError if the object is a built-in module, class, or function.


Get information about a frame or traceback object. A named tuple Traceback(filename, lineno, function, code_context, index) is returned.


Get the names and default values of a Python function’s parameters. A named tuple is returned:
FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
annotations)
args is a list of the positional parameter names. varargs is the name of the * parameter or None if arbitrary positional arguments are not accepted. varkw is the name of the ** parameter or None if arbitrary keyword arguments are not accepted. defaults is an n-tuple of default argument values corresponding to the last n positional parameters, or None if there are no such defaults defined. kwonlyargs is a list of keyword-only parameter names in declaration order. kwonlydefaults is a dictionary mapping parameter names from kwonlyargs to the default values used if no argument is supplied. annotations is a dictionary mapping parameter names to annotations. The special key "return" is used to report the function return value annotation (if any).
Note that signature() and Signature Object provide the recommended API for callable introspection, and support additional behaviours (like positional-only arguments) that are sometimes encountered in extension module APIs. This function is retained primarily for use in code that needs to maintain compatibility with the Python 2 inspect module API.
Changed in version 3.4: This function is now based on signature(), but still ignores __wrapped__ attributes and includes the already bound first parameter in the signature output for bound methods.
Changed in version 3.6: This method was previously documented as deprecated in favour of signature() in Python 3.5, but that decision has been reversed in order to restore a clearly supported standard interface for single-source Python 2/3 code migrating away from the legacy getargspec() API.
Changed in version 3.7: Python only explicitly guaranteed that it preserved the declaration order of keyword-only parameters as of version 3.7, although in practice this order had always been preserved in Python 3.


Get the mapping of live local variables in generator to their current values. A dictionary is returned that maps from variable names to values. This is the equivalent of calling locals() in the body of the generator, and all the same caveats apply.
If generator is a generator with no currently associated frame, then an empty dictionary is returned. TypeError is raised if generator is not a Python generator object.
CPython implementation detail: This function relies on the generator exposing a Python stack frame for introspection, which isn’t guaranteed to be the case in all implementations of Python. In such cases, this function will always return an empty dictionary.
New in version 3.3.


Get current state of a generator-iterator.
New in version 3.2.


Get a list of frame records for a traceback’s frame and all inner frames. These frames represent calls made as a consequence of frame. The first entry in the list represents traceback; the last entry represents where the exception was raised.
Changed in version 3.5: A list of named tuples FrameInfo(frame, filename, lineno, function, code_context, index) is returned.


Return all the members of an object in a list of (name, value) pairs sorted by name. If the optional predicate argument—which will be called with the value object of each member—is supplied, only members for which the predicate returns a true value are included.
Note
getmembers() will only return class attributes defined in the metaclass when the argument is a class and those attributes have been listed in the metaclass’ custom __dir__().


Try to guess which module an object was defined in.


Return the name of the module named by the file path, without including the names of enclosing packages. The file extension is checked against all of the entries in importlib.machinery.all_suffixes(). If it matches, the final path component is returned with the extension removed. Otherwise, None is returned.
Note that this function only returns a meaningful name for actual Python modules - paths that potentially refer to Python packages will still return None.
Changed in version 3.3: The function is based directly on importlib.


Return a tuple of class cls’s base classes, including cls, in method resolution order. No class appears more than once in this tuple. Note that the method resolution order depends on cls’s type. Unless a very peculiar user-defined metatype is in use, cls will be the first element of the tuple.


Get a list of frame records for a frame and all outer frames. These frames represent the calls that lead to the creation of frame. The first entry in the returned list represents frame; the last entry represents the outermost call on frame’s stack.
Changed in version 3.5: A list of named tuples FrameInfo(frame, filename, lineno, function, code_context, index) is returned.


Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An OSError is raised if the source code cannot be retrieved.
Changed in version 3.3: OSError is raised instead of IOError, now an alias of the former.


Return the name of the Python source file in which an object was defined. This will fail with a TypeError if the object is a built-in module, class, or function.


Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An OSError is raised if the source code cannot be retrieved.
Changed in version 3.3: OSError is raised instead of IOError, now an alias of the former.


Return True if the object is an abstract base class.


Return True if the object is an asynchronous generator iterator created by an asynchronous generator function.
New in version 3.6.


Return True if the object is an asynchronous generator function, for example:
New in version 3.6.
Changed in version 3.8: Functions wrapped in functools.partial() now return True if the wrapped function is a asynchronous generator function.


Return True if the object can be used in await expression.
Can also be used to distinguish generator-based coroutines from regular generators:
New in version 3.5.


Return True if the object is a built-in function or a bound built-in method.


Return True if the object is a class, whether built-in or created in Python code.


Return True if the object is a coroutine created by an async def function.
New in version 3.5.


Return True if the object is a coroutine function (a function defined with an async def syntax).
New in version 3.5.
Changed in version 3.8: Functions wrapped in functools.partial() now return True if the wrapped function is a coroutine function.


Return True if the object is a data descriptor.
Data descriptors have a __set__ or a __delete__ method. Examples are properties (defined in Python), getsets, and members. The latter two are defined in C and there are more specific tests available for those types, which is robust across Python implementations. Typically, data descriptors will also have __name__ and __doc__ attributes (properties, getsets, and members have both of these attributes), but this is not guaranteed.


Return True if the object is a Python function, which includes functions created by a lambda expression.


Return True if the object is a generator.


Return True if the object is a Python generator function.
Changed in version 3.8: Functions wrapped in functools.partial() now return True if the wrapped function is a Python generator function.


Return True if the object is a getset descriptor.
CPython implementation detail: getsets are attributes defined in extension modules via PyGetSetDef structures. For Python implementations without such types, this method will always return False.


Return True if the object is a member descriptor.
CPython implementation detail: Member descriptors are attributes defined in extension modules via PyMemberDef structures. For Python implementations without such types, this method will always return False.


Return True if the object is a bound method written in Python.


Return True if the object is a method descriptor, but not if ismethod(), isclass(), isfunction() or isbuiltin() are true.
This, for example, is true of int.__add__. An object passing this test has a __get__() method but not a __set__() method, but beyond that the set of attributes varies. A __name__ attribute is usually sensible, and __doc__ often is.
Methods implemented via descriptors that also pass one of the other tests return False from the ismethoddescriptor() test, simply because the other tests promise more – you can, e.g., count on having the __func__ attribute (etc) when an object passes ismethod().


Return True if the object is a user-defined or built-in function or method.


Return True if the object is a traceback.


Parameter objects are immutable. Instead of modifying a Parameter object, you can use Parameter.replace() to create a modified copy.
Changed in version 3.5: Parameter objects are picklable and hashable.
A special class-level marker to specify absence of default values and annotations.
The name of the parameter as a string. The name must be a valid Python identifier.
CPython implementation detail: CPython generates implicit parameter names of the form .0 on the code objects used to implement comprehensions and generator expressions.
Changed in version 3.6: These parameter names are exposed by this module as names like implicit0.
The default value for the parameter. If the parameter has no default value, this attribute is set to Parameter.empty.
The annotation for the parameter. If the parameter has no annotation, this attribute is set to Parameter.empty.
Describes how argument values are bound to the parameter. Possible values (accessible via Parameter, like Parameter.KEYWORD_ONLY):
Name
Meaning
POSITIONAL_ONLY
Value must be supplied as a positional argument. Positional only parameters are those which appear before a / entry (if present) in a Python function definition.
POSITIONAL_OR_KEYWORD
Value may be supplied as either a keyword or positional argument (this is the standard binding behaviour for functions implemented in Python.)
VAR_POSITIONAL
A tuple of positional arguments that aren’t bound to any other parameter. This corresponds to a *args parameter in a Python function definition.
KEYWORD_ONLY
Value must be supplied as a keyword argument. Keyword only parameters are those which appear after a * or *args entry in a Python function definition.
VAR_KEYWORD
A dict of keyword arguments that aren’t bound to any other parameter. This corresponds to a **kwargs parameter in a Python function definition.
Example: print all keyword-only arguments without default values:
Describes a enum value of Parameter.kind.
New in version 3.8.
Example: print all descriptions of arguments:
Create a new Parameter instance based on the instance replaced was invoked on. To override a Parameter attribute, pass the corresponding argument. To remove a default value or/and an annotation from a Parameter, pass Parameter.empty.
Changed in version 3.4: In Python 3.3 Parameter objects were allowed to have name set to None if their kind was set to POSITIONAL_ONLY. This is no longer permitted.


The annotation for the parameter. If the parameter has no annotation, this attribute is set to Parameter.empty.


The default value for the parameter. If the parameter has no default value, this attribute is set to Parameter.empty.


A special class-level marker to specify absence of default values and annotations.


Describes how argument values are bound to the parameter. Possible values (accessible via Parameter, like Parameter.KEYWORD_ONLY):
Name
Meaning
POSITIONAL_ONLY
Value must be supplied as a positional argument. Positional only parameters are those which appear before a / entry (if present) in a Python function definition.
POSITIONAL_OR_KEYWORD
Value may be supplied as either a keyword or positional argument (this is the standard binding behaviour for functions implemented in Python.)
VAR_POSITIONAL
A tuple of positional arguments that aren’t bound to any other parameter. This corresponds to a *args parameter in a Python function definition.
KEYWORD_ONLY
Value must be supplied as a keyword argument. Keyword only parameters are those which appear after a * or *args entry in a Python function definition.
VAR_KEYWORD
A dict of keyword arguments that aren’t bound to any other parameter. This corresponds to a **kwargs parameter in a Python function definition.
Example: print all keyword-only arguments without default values:


Describes a enum value of Parameter.kind.
New in version 3.8.
Example: print all descriptions of arguments:


The name of the parameter as a string. The name must be a valid Python identifier.
CPython implementation detail: CPython generates implicit parameter names of the form .0 on the code objects used to implement comprehensions and generator expressions.
Changed in version 3.6: These parameter names are exposed by this module as names like implicit0.


Create a new Parameter instance based on the instance replaced was invoked on. To override a Parameter attribute, pass the corresponding argument. To remove a default value or/and an annotation from a Parameter, pass Parameter.empty.
Changed in version 3.4: In Python 3.3 Parameter objects were allowed to have name set to None if their kind was set to POSITIONAL_ONLY. This is no longer permitted.


A Signature object represents the call signature of a function and its return annotation. For each parameter accepted by the function it stores a Parameter object in its parameters collection.
The optional parameters argument is a sequence of Parameter objects, which is validated to check that there are no parameters with duplicate names, and that the parameters are in the right order, i.e. positional-only first, then positional-or-keyword, and that parameters with defaults follow parameters without defaults.
The optional return_annotation argument, can be an arbitrary Python object, is the “return” annotation of the callable.
Signature objects are immutable. Use Signature.replace() to make a modified copy.
Changed in version 3.5: Signature objects are picklable and hashable.
A special class-level marker to specify absence of a return annotation.
An ordered mapping of parameters’ names to the corresponding Parameter objects. Parameters appear in strict definition order, including keyword-only parameters.
Changed in version 3.7: Python only explicitly guaranteed that it preserved the declaration order of keyword-only parameters as of version 3.7, although in practice this order had always been preserved in Python 3.
The “return” annotation for the callable. If the callable has no “return” annotation, this attribute is set to Signature.empty.
Create a mapping from positional and keyword arguments to parameters. Returns BoundArguments if *args and **kwargs match the signature, or raises a TypeError.
Works the same way as Signature.bind(), but allows the omission of some required arguments (mimics functools.partial() behavior.) Returns BoundArguments, or raises a TypeError if the passed arguments do not match the signature.
Create a new Signature instance based on the instance replace was invoked on. It is possible to pass different parameters and/or return_annotation to override the corresponding properties of the base signature. To remove return_annotation from the copied Signature, pass in Signature.empty.
Return a Signature (or its subclass) object for a given callable obj. Pass follow_wrapped=False to get a signature of obj without unwrapping its __wrapped__ chain.
This method simplifies subclassing of Signature:
New in version 3.5.


Return a Signature object for the given callable:
Accepts a wide range of Python callables, from plain functions and classes to functools.partial() objects.
Raises ValueError if no signature can be provided, and TypeError if that type of object is not supported.
A slash(/) in the signature of a function denotes that the parameters prior to it are positional-only. For more info, see the FAQ entry on positional-only parameters.
New in version 3.5: follow_wrapped parameter. Pass False to get a signature of callable specifically (callable.__wrapped__ will not be used to unwrap decorated callables.)
Note
Some callables may not be introspectable in certain implementations of Python. For example, in CPython, some built-in functions defined in C provide no metadata about their arguments.


Create a mapping from positional and keyword arguments to parameters. Returns BoundArguments if *args and **kwargs match the signature, or raises a TypeError.


Works the same way as Signature.bind(), but allows the omission of some required arguments (mimics functools.partial() behavior.) Returns BoundArguments, or raises a TypeError if the passed arguments do not match the signature.


A special class-level marker to specify absence of a return annotation.


Return a Signature (or its subclass) object for a given callable obj. Pass follow_wrapped=False to get a signature of obj without unwrapping its __wrapped__ chain.
This method simplifies subclassing of Signature:
New in version 3.5.


An ordered mapping of parameters’ names to the corresponding Parameter objects. Parameters appear in strict definition order, including keyword-only parameters.
Changed in version 3.7: Python only explicitly guaranteed that it preserved the declaration order of keyword-only parameters as of version 3.7, although in practice this order had always been preserved in Python 3.


Create a new Signature instance based on the instance replace was invoked on. It is possible to pass different parameters and/or return_annotation to override the corresponding properties of the base signature. To remove return_annotation from the copied Signature, pass in Signature.empty.


The “return” annotation for the callable. If the callable has no “return” annotation, this attribute is set to Signature.empty.


Return a list of frame records for the caller’s stack. The first entry in the returned list represents the caller; the last entry represents the outermost call on the stack.
Changed in version 3.5: A list of named tuples FrameInfo(frame, filename, lineno, function, code_context, index) is returned.


Return a list of frame records for the stack between the current frame and the frame in which an exception currently being handled was raised in. The first entry in the list represents the caller; the last entry represents where the exception was raised.
Changed in version 3.5: A list of named tuples FrameInfo(frame, filename, lineno, function, code_context, index) is returned.


Get the object wrapped by func. It follows the chain of __wrapped__ attributes returning the last object in the chain.
stop is an optional callback accepting an object in the wrapper chain as its sole argument that allows the unwrapping to be terminated early if the callback returns a true value. If the callback never returns a true value, the last object in the chain is returned as usual. For example, signature() uses this to stop unwrapping if any object in the chain has a __signature__ attribute defined.
ValueError is raised if a cycle is encountered.
New in version 3.4.


The class to which a class instance belongs.


Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x defines __int__(), int(x) returns x.__int__(). If x defines __index__(), it returns x.__index__(). If x defines __trunc__(), it returns x.__trunc__(). For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35. The default base is 10. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8).
The integer type is described in Numeric Types — int, float, complex.
Changed in version 3.4: If base is not an instance of int and the base object has a base.__index__ method, that method is called to obtain an integer for the base. Previous versions used base.__int__ instead of base.__index__.
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 __int__() is not defined.


Return a pair of integers whose ratio is exactly equal to the original integer and with a positive denominator. The integer ratio of integers (whole numbers) is always the integer as the numerator and 1 as the denominator.
New in version 3.8.


Return the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros:
More precisely, if x is nonzero, then x.bit_length() is the unique positive integer k such that 2**(k-1) <= abs(x) < 2**k. Equivalently, when abs(x) is small enough to have a correctly rounded logarithm, then k = 1 + int(log(abs(x), 2)). If x is zero, then x.bit_length() returns 0.
Equivalent to:
New in version 3.1.


Return the integer represented by the given array of bytes.
The argument bytes must either be a bytes-like object or an iterable producing bytes.
The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.
The signed argument indicates whether two’s complement is used to represent the integer.
New in version 3.2.


Return an array of bytes representing an integer.
The integer is represented using length bytes. An OverflowError is raised if the integer is not representable with the given number of bytes.
The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.
The signed argument determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised. The default value for signed is False.
New in version 3.2.


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.


Source code: Lib/io.py
The io module provides Python’s main facilities for dealing with various types of I/O. There are three main types of I/O: text I/O, binary I/O and raw I/O. These are generic categories, and various backing stores can be used for each of them. A concrete object belonging to any of these categories is called a file object. Other common terms are stream and file-like object.
Independent of its category, each concrete stream object will also have various capabilities: it can be read-only, write-only, or read-write. It can also allow arbitrary random access (seeking forwards or backwards to any location), or only sequential access (for example in the case of a socket or pipe).
All streams are careful about the type of data you give to them. For example giving a str object to the write() method of a binary stream will raise a TypeError. So will giving a bytes object to the write() method of a text stream.
Changed in version 3.3: Operations that used to raise IOError now raise OSError, since IOError is now an alias of OSError.
Text I/O expects and produces str objects. This means that whenever the backing store is natively made of bytes (such as in the case of a file), encoding and decoding of data is made transparently as well as optional translation of platform-specific newline characters.
The easiest way to create a text stream is with open(), optionally specifying an encoding:
In-memory text streams are also available as StringIO objects:
The text stream API is described in detail in the documentation of TextIOBase.
Binary I/O (also called buffered I/O) expects bytes-like objects and produces bytes objects. No encoding, decoding, or newline translation is performed. This category of streams can be used for all kinds of non-text data, and also when manual control over the handling of text data is desired.
The easiest way to create a binary stream is with open() with 'b' in the mode string:
In-memory binary streams are also available as BytesIO objects:
The binary stream API is described in detail in the docs of BufferedIOBase.
Other library modules may provide additional ways to create text or binary streams. See socket.socket.makefile() for example.
Raw I/O (also called unbuffered I/O) is generally used as a low-level building-block for binary and text streams; it is rarely useful to directly manipulate a raw stream from user code. Nevertheless, you can create a raw stream by opening a file in binary mode with buffering disabled:
The raw stream API is described in detail in the docs of RawIOBase.
An int containing the default buffer size used by the module’s buffered I/O classes. open() uses the file’s blksize (as obtained by os.stat()) if possible.
This is an alias for the builtin open() function.
This function raises an auditing event open with arguments path, mode and flags. The mode and flags arguments may have been modified or inferred from the original call.
Opens the provided file with mode 'rb'. This function should be used when the intent is to treat the contents as executable code.
path should be a str and an absolute path.
The behavior of this function may be overridden by an earlier call to the PyFile_SetOpenCodeHook(). However, assuming that path is a str and an absolute path, open_code(path) should always behave the same as open(path, 'rb'). Overriding the behavior is intended for additional validation or preprocessing of the file.
New in version 3.8.
This is a compatibility alias for the builtin BlockingIOError exception.
An exception inheriting OSError and ValueError that is raised when an unsupported operation is called on a stream.
See also
contains the standard IO streams: sys.stdin, sys.stdout, and sys.stderr.
The implementation of I/O streams is organized as a hierarchy of classes. First abstract base classes (ABCs), which are used to specify the various categories of streams, then concrete classes providing the standard stream implementations.
Note
The abstract base classes also provide default implementations of some methods in order to help implementation of concrete stream classes. For example, BufferedIOBase provides unoptimized implementations of readinto() and readline().
At the top of the I/O hierarchy is the abstract base class IOBase. It defines the basic interface to a stream. Note, however, that there is no separation between reading and writing to streams; implementations are allowed to raise UnsupportedOperation if they do not support a given operation.
The RawIOBase ABC extends IOBase. It deals with the reading and writing of bytes to a stream. FileIO subclasses RawIOBase to provide an interface to files in the machine’s file system.
The BufferedIOBase ABC extends IOBase. It deals with buffering on a raw binary stream (RawIOBase). Its subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer raw binary streams that are readable, writable, and both readable and writable, respectively. BufferedRandom provides a buffered interface to seekable streams. Another BufferedIOBase subclass, BytesIO, is a stream of in-memory bytes.
The TextIOBase ABC extends IOBase. It deals with streams whose bytes represent text, and handles encoding and decoding to and from strings. TextIOWrapper, which extends TextIOBase, is a buffered text interface to a buffered raw stream (BufferedIOBase). Finally, StringIO is an in-memory stream for text.
Argument names are not part of the specification, and only the arguments of open() are intended to be used as keyword arguments.
The following table summarizes the ABCs provided by the io module:
ABC
Inherits
Stub Methods
Mixin Methods and Properties
IOBase
fileno, seek, and truncate
close, closed, __enter__, __exit__, flush, isatty, __iter__, __next__, readable, readline, readlines, seekable, tell, writable, and writelines
RawIOBase
IOBase
readinto and write
Inherited IOBase methods, read, and readall
BufferedIOBase
IOBase
detach, read, read1, and write
Inherited IOBase methods, readinto, and readinto1
TextIOBase
IOBase
detach, read, readline, and write
Inherited IOBase methods, encoding, errors, and newlines
The abstract base class for all I/O classes, acting on streams of bytes. There is no public constructor.
This class provides empty abstract implementations for many methods that derived classes can override selectively; the default implementations represent a file that cannot be read, written or seeked.
Even though IOBase does not declare read() or write() because their signatures will vary, implementations and clients should consider those methods part of the interface. Also, implementations may raise a ValueError (or UnsupportedOperation) when operations they do not support are called.
The basic type used for binary data read from or written to a file is bytes. Other bytes-like objects are accepted as method arguments too. Text I/O classes work with str data.
Note that calling any method (even inquiries) on a closed stream is undefined. Implementations may raise ValueError in this case.
IOBase (and its subclasses) supports the iterator protocol, meaning that an IOBase object can be iterated over yielding the lines in a stream. Lines are defined slightly differently depending on whether the stream is a binary stream (yielding bytes), or a text stream (yielding character strings). See readline() below.
IOBase is also a context manager and therefore supports the with statement. In this example, file is closed after the with statement’s suite is finished—even if an exception occurs:
IOBase provides these data attributes and methods:
Flush and close this stream. This method has no effect if the file is already closed. Once the file is closed, any operation on the file (e.g. reading or writing) will raise a ValueError.
As a convenience, it is allowed to call this method more than once; only the first call, however, will have an effect.
True if the stream is closed.
Return the underlying file descriptor (an integer) of the stream if it exists. An OSError is raised if the IO object does not use a file descriptor.
Flush the write buffers of the stream if applicable. This does nothing for read-only and non-blocking streams.
Return True if the stream is interactive (i.e., connected to a terminal/tty device).
Return True if the stream can be read from. If False, read() will raise OSError.
Read and return one line from the stream. If size is specified, at most size bytes will be read.
The line terminator is always b'\n' for binary files; for text files, the newline argument to open() can be used to select the line terminator(s) recognized.
Read and return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.
Note that it’s already possible to iterate on file objects using for
line in file: ... without calling file.readlines().
Change the stream position to the given byte offset. offset is interpreted relative to the position indicated by whence. The default value for whence is SEEK_SET. Values for whence are:
Return the new absolute position.
New in version 3.1: The SEEK_* constants.
New in version 3.3: Some operating systems could support additional values, like os.SEEK_HOLE or os.SEEK_DATA. The valid values for a file could depend on it being open in text or binary mode.
Return True if the stream supports random access. If False, seek(), tell() and truncate() will raise OSError.
Return the current stream position.
Resize the stream to the given size in bytes (or the current position if size is not specified). The current stream position isn’t changed. This resizing can extend or reduce the current file size. In case of extension, the contents of the new file area depend on the platform (on most systems, additional bytes are zero-filled). The new file size is returned.
Changed in version 3.5: Windows will now zero-fill files when extending.
Return True if the stream supports writing. If False, write() and truncate() will raise OSError.
Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.
Prepare for object destruction. IOBase provides a default implementation of this method that calls the instance’s close() method.
Base class for raw binary streams. It inherits IOBase. There is no public constructor.
Raw binary streams typically provide low-level access to an underlying OS device or API, and do not try to encapsulate it in high-level primitives (this functionality is done at a higher-level in buffered binary streams and text streams, described later in this page).
RawIOBase provides these methods in addition to those from IOBase:
Read up to size bytes from the object and return them. As a convenience, if size is unspecified or -1, all bytes until EOF are returned. Otherwise, only one system call is ever made. Fewer than size bytes may be returned if the operating system call returns fewer than size bytes.
If 0 bytes are returned, and size was not 0, this indicates end of file. If the object is in non-blocking mode and no bytes are available, None is returned.
The default implementation defers to readall() and readinto().
Read and return all the bytes from the stream until EOF, using multiple calls to the stream if necessary.
Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. For example, b might be a bytearray. If the object is in non-blocking mode and no bytes are available, None is returned.
Write the given bytes-like object, b, to the underlying raw stream, and return the number of bytes written. This can be less than the length of b in bytes, depending on specifics of the underlying raw stream, and especially if it is in non-blocking mode. None is returned if the raw stream is set not to block and no single byte could be readily written to it. The caller may release or mutate b after this method returns, so the implementation should only access b during the method call.
Base class for binary streams that support some kind of buffering. It inherits IOBase. There is no public constructor.
The main difference with RawIOBase is that methods read(), readinto() and write() will try (respectively) to read as much input as requested or to consume all given output, at the expense of making perhaps more than one system call.
In addition, those methods can raise BlockingIOError if the underlying raw stream is in non-blocking mode and cannot take or give enough data; unlike their RawIOBase counterparts, they will never return None.
Besides, the read() method does not have a default implementation that defers to readinto().
A typical BufferedIOBase implementation should not inherit from a RawIOBase implementation, but wrap one, like BufferedWriter and BufferedReader do.
BufferedIOBase provides or overrides these data attributes and methods in addition to those from IOBase:
The underlying raw stream (a RawIOBase instance) that BufferedIOBase deals with. This is not part of the BufferedIOBase API and may not exist on some implementations.
Separate the underlying raw stream from the buffer and return it.
After the raw stream has been detached, the buffer is in an unusable state.
Some buffers, like BytesIO, do not have the concept of a single raw stream to return from this method. They raise UnsupportedOperation.
New in version 3.1.
Read and return up to size bytes. If the argument is omitted, None, or negative, data is read and returned until EOF is reached. An empty bytes object is returned if the stream is already at EOF.
If the argument is positive, and the underlying raw stream is not interactive, multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first). But for interactive raw streams, at most one raw read will be issued, and a short result does not imply that EOF is imminent.
A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.
Read and return up to size bytes, with at most one call to the underlying raw stream’s read() (or readinto()) method. This can be useful if you are implementing your own buffering on top of a BufferedIOBase object.
If size is -1 (the default), an arbitrary number of bytes are returned (more than zero unless EOF is reached).
Read bytes into a pre-allocated, writable bytes-like object b and return the number of bytes read. For example, b might be a bytearray.
Like read(), multiple reads may be issued to the underlying raw stream, unless the latter is interactive.
A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.
Read bytes into a pre-allocated, writable bytes-like object b, using at most one call to the underlying raw stream’s read() (or readinto()) method. Return the number of bytes read.
A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.
New in version 3.5.
Write the given bytes-like object, b, and return the number of bytes written (always equal to the length of b in bytes, since if the write fails an OSError will be raised). Depending on the actual implementation, these bytes may be readily written to the underlying stream, or held in a buffer for performance and latency reasons.
When in non-blocking mode, a BlockingIOError is raised if the data needed to be written to the raw stream but it couldn’t accept all the data without blocking.
The caller may release or mutate b after this method returns, so the implementation should only access b during the method call.
A raw binary stream representing an OS-level file containing bytes data. It inherits RawIOBase.
The name can be one of two things:
The mode can be 'r', 'w', 'x' or 'a' for reading (default), writing, exclusive creation or appending. The file will be created if it doesn’t exist when opened for writing or appending; it will be truncated when opened for writing. FileExistsError will be raised if it already exists when opened for creating. Opening a file for creating implies writing, so this mode behaves in a similar way to 'w'. Add a '+' to the mode to allow simultaneous reading and writing.
The read() (when called with a positive argument), readinto() and write() methods on this class will only make one system call.
A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (name, flags). opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None).
The newly created file is non-inheritable.
See the open() built-in function for examples on using the opener parameter.
Changed in version 3.3: The opener parameter was added. The 'x' mode was added.
Changed in version 3.4: The file is now non-inheritable.
FileIO provides these data attributes in addition to those from RawIOBase and IOBase:
The mode as given in the constructor.
The file name. This is the file descriptor of the file when no name is given in the constructor.
Buffered I/O streams provide a higher-level interface to an I/O device than raw I/O does.
A binary stream using an in-memory bytes buffer. It inherits BufferedIOBase. The buffer is discarded when the close() method is called.
The optional argument initial_bytes is a bytes-like object that contains initial data.
BytesIO provides or overrides these methods in addition to those from BufferedIOBase and IOBase:
Return a readable and writable view over the contents of the buffer without copying them. Also, mutating the view will transparently update the contents of the buffer:
Note
As long as the view exists, the BytesIO object cannot be resized or closed.
New in version 3.2.
Return bytes containing the entire contents of the buffer.
In BytesIO, this is the same as read().
Changed in version 3.7: The size argument is now optional.
In BytesIO, this is the same as readinto().
New in version 3.5.
A buffered binary stream providing higher-level access to a readable, non seekable RawIOBase raw binary stream. It inherits BufferedIOBase.
When reading data from this object, a larger amount of data may be requested from the underlying raw stream, and kept in an internal buffer. The buffered data can then be returned directly on subsequent reads.
The constructor creates a BufferedReader for the given readable raw stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE is used.
BufferedReader provides or overrides these methods in addition to those from BufferedIOBase and IOBase:
Return bytes from the stream without advancing the position. At most one single read on the raw stream is done to satisfy the call. The number of bytes returned may be less or more than requested.
Read and return size bytes, or if size is not given or negative, until EOF or if the read call would block in non-blocking mode.
Read and return up to size bytes with only one call on the raw stream. If at least one byte is buffered, only buffered bytes are returned. Otherwise, one raw stream read call is made.
Changed in version 3.7: The size argument is now optional.
A buffered binary stream providing higher-level access to a writeable, non seekable RawIOBase raw binary stream. It inherits BufferedIOBase.
When writing to this object, data is normally placed into an internal buffer. The buffer will be written out to the underlying RawIOBase object under various conditions, including:
The constructor creates a BufferedWriter for the given writeable raw stream. If the buffer_size is not given, it defaults to DEFAULT_BUFFER_SIZE.
BufferedWriter provides or overrides these methods in addition to those from BufferedIOBase and IOBase:
Force bytes held in the buffer into the raw stream. A BlockingIOError should be raised if the raw stream blocks.
Write the bytes-like object, b, and return the number of bytes written. When in non-blocking mode, a BlockingIOError is raised if the buffer needs to be written out but the raw stream blocks.
A buffered binary stream providing higher-level access to a seekable RawIOBase raw binary stream. It inherits BufferedReader and BufferedWriter.
The constructor creates a reader and writer for a seekable raw stream, given in the first argument. If the buffer_size is omitted it defaults to DEFAULT_BUFFER_SIZE.
BufferedRandom is capable of anything BufferedReader or BufferedWriter can do. In addition, seek() and tell() are guaranteed to be implemented.
A buffered binary stream providing higher-level access to two non seekable RawIOBase raw binary streams—one readable, the other writeable. It inherits BufferedIOBase.
reader and writer are RawIOBase objects that are readable and writeable respectively. If the buffer_size is omitted it defaults to DEFAULT_BUFFER_SIZE.
BufferedRWPair implements all of BufferedIOBase’s methods except for detach(), which raises UnsupportedOperation.
Warning
BufferedRWPair does not attempt to synchronize accesses to its underlying raw streams. You should not pass it the same object as reader and writer; use BufferedRandom instead.
Base class for text streams. This class provides a character and line based interface to stream I/O. It inherits IOBase. There is no public constructor.
TextIOBase provides or overrides these data attributes and methods in addition to those from IOBase:
The name of the encoding used to decode the stream’s bytes into strings, and to encode strings into bytes.
The error setting of the decoder or encoder.
A string, a tuple of strings, or None, indicating the newlines translated so far. Depending on the implementation and the initial constructor flags, this may not be available.
The underlying binary buffer (a BufferedIOBase instance) that TextIOBase deals with. This is not part of the TextIOBase API and may not exist in some implementations.
Separate the underlying binary buffer from the TextIOBase and return it.
After the underlying buffer has been detached, the TextIOBase is in an unusable state.
Some TextIOBase implementations, like StringIO, may not have the concept of an underlying buffer and calling this method will raise UnsupportedOperation.
New in version 3.1.
Read and return at most size characters from the stream as a single str. If size is negative or None, reads until EOF.
Read until newline or EOF and return a single str. If the stream is already at EOF, an empty string is returned.
If size is specified, at most size characters will be read.
Change the stream position to the given offset. Behaviour depends on the whence parameter. The default value for whence is SEEK_SET.
Return the new absolute position as an opaque number.
New in version 3.1: The SEEK_* constants.
Return the current stream position as an opaque number. The number does not usually represent a number of bytes in the underlying binary storage.
Write the string s to the stream and return the number of characters written.
A buffered text stream providing higher-level access to a BufferedIOBase buffered binary stream. It inherits TextIOBase.
encoding gives the name of the encoding that the stream will be decoded or encoded with. It defaults to locale.getpreferredencoding(False).
errors is an optional string that specifies how encoding and decoding errors are to be handled. Pass 'strict' to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ignore errors. (Note that ignoring encoding errors can lead to data loss.) 'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data. 'backslashreplace' causes malformed data to be replaced by a backslashed escape sequence. When writing, 'xmlcharrefreplace' (replace with the appropriate XML character reference) or 'namereplace' (replace with \N{...} escape sequences) can be used. Any other error handling name that has been registered with codecs.register_error() is also valid.
newline controls how line endings are handled. It can be None, '', '\n', '\r', and '\r\n'. It works as follows:
If line_buffering is True, flush() is implied when a call to write contains a newline character or a carriage return.
If write_through is True, calls to write() are guaranteed not to be buffered: any data written on the TextIOWrapper object is immediately handled to its underlying binary buffer.
Changed in version 3.3: The write_through argument has been added.
Changed in version 3.3: The default encoding is now locale.getpreferredencoding(False) instead of locale.getpreferredencoding(). Don’t change temporary the locale encoding using locale.setlocale(), use the current locale encoding instead of the user preferred encoding.
TextIOWrapper provides these data attributes and methods in addition to those from TextIOBase and IOBase:
Whether line buffering is enabled.
Whether writes are passed immediately to the underlying binary buffer.
New in version 3.7.
Reconfigure this text stream using new settings for encoding, errors, newline, line_buffering and write_through.
Parameters not specified keep current settings, except errors='strict' is used when encoding is specified but errors is not specified.
It is not possible to change the encoding or newline if some data has already been read from the stream. On the other hand, changing encoding after write is possible.
This method does an implicit stream flush before setting the new parameters.
New in version 3.7.
A text stream using an in-memory text buffer. It inherits TextIOBase.
The text buffer is discarded when the close() method is called.
The initial value of the buffer can be set by providing initial_value. If newline translation is enabled, newlines will be encoded as if by write(). The stream is positioned at the start of the buffer.
The newline argument works like that of TextIOWrapper, except that when writing output to the stream, if newline is None, newlines are written as \n on all platforms.
StringIO provides this method in addition to those from TextIOBase and IOBase:
Return a str containing the entire contents of the buffer. Newlines are decoded as if by read(), although the stream position is not changed.
Example usage:
A helper codec that decodes newlines for universal newlines mode. It inherits codecs.IncrementalDecoder.
This section discusses the performance of the provided concrete I/O implementations.
By reading and writing only large chunks of data even when the user asks for a single byte, buffered I/O hides any inefficiency in calling and executing the operating system’s unbuffered I/O routines. The gain depends on the OS and the kind of I/O which is performed. For example, on some modern OSes such as Linux, unbuffered disk I/O can be as fast as buffered I/O. The bottom line, however, is that buffered I/O offers predictable performance regardless of the platform and the backing device. Therefore, it is almost always preferable to use buffered I/O rather than unbuffered I/O for binary data.
Text I/O over a binary storage (such as a file) is significantly slower than binary I/O over the same storage, because it requires conversions between unicode and binary data using a character codec. This can become noticeable handling huge amounts of text data like large log files. Also, TextIOWrapper.tell() and TextIOWrapper.seek() are both quite slow due to the reconstruction algorithm used.
StringIO, however, is a native in-memory unicode container and will exhibit similar speed to BytesIO.
FileIO objects are thread-safe to the extent that the operating system calls (such as read(2) under Unix) they wrap are thread-safe too.
Binary buffered objects (instances of BufferedReader, BufferedWriter, BufferedRandom and BufferedRWPair) protect their internal structures using a lock; it is therefore safe to call them from multiple threads at once.
TextIOWrapper objects are not thread-safe.
Binary buffered objects (instances of BufferedReader, BufferedWriter, BufferedRandom and BufferedRWPair) are not reentrant. While reentrant calls will not happen in normal situations, they can arise from doing I/O in a signal handler. If a thread tries to re-enter a buffered object which it is already accessing, a RuntimeError is raised. Note this doesn’t prohibit a different thread from entering the buffered object.
The above implicitly extends to text files, since the open() function will wrap a buffered object inside a TextIOWrapper. This includes standard streams and therefore affects the built-in print() function as well.


This is a compatibility alias for the builtin BlockingIOError exception.