New in version 2.1.
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 sixteen 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:
|__file__||filename (missing for built-in modules)|
|__module__||name of module in which this class was defined|
|__name__||name with which this method was defined|
|im_class||class object that asked for this method||(1)|
|im_func or __func__||function object containing implementation of method|
|im_self or __self__||instance to which this method is bound, or None|
|__name__||name with which this function was defined|
|func_code||code object containing compiled function bytecode|
|func_defaults||tuple of any default values for arguments|
|func_doc||(same as __doc__)|
|func_globals||global namespace in which this function was defined|
|func_name||(same as __name__)|
|generator||__iter__||defined to support iteration over container|
|close||raises new GeneratorExit exception inside the generator to terminate the iteration|
|gi_frame||frame object or possibly None once the generator has been exhausted|
|gi_running||set to 1 when generator is executing, 0 otherwise|
|next||return the next item from the container|
|send||resumes the generator and “sends” a value that becomes the result of the current yield-expression|
|throw||used to raise an exception inside the generator|
|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_exc_traceback||traceback if raised in this frame, or None|
|f_exc_type||exception type if raised in this frame, or None|
|f_exc_value||exception value if raised in this frame, or None|
|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_restricted||0 or 1 if frame is in restricted execution mode|
|f_trace||tracing function for this frame, or None|
|code||co_argcount||number of arguments (not including * or ** args)|
|co_code||string of raw compiled bytecode|
|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: 1=optimized | 2=newlocals | 4=*arg | 8=**arg|
|co_lnotab||encoded mapping of line numbers to bytecode indices|
|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|
|__name__||original name of this function or method|
|__self__||instance to which a method is bound, or None|
Changed in version 2.2: im_class used to refer to the class that defined the method.
Return all the members of an object in a list of (name, value) pairs sorted by name. If the optional predicate argument is supplied, only members for which the predicate returns a true value are included.
Return a tuple of values that describe how Python will interpret the file identified by path if it is a module, or None if it would not be identified as a module. The return tuple is (name, suffix, mode, mtype), where name is the name of the module without the name of any enclosing package, suffix is the trailing part of the file name (which may not be a dot-delimited extension), mode is the open() mode that would be used ('r' or 'rb'), and mtype is an integer giving the type of the module. mtype will have a value which can be compared to the constants defined in the imp module; see the documentation for that module for more information on module types.
Changed in version 2.6: Returns a named tuple ModuleInfo(name, suffix, mode, module_type).
Return true if the object is a Python generator function.
New in version 2.6.
Return true if the object is a generator.
New in version 2.6.
Return true if the object is an abstract base class.
New in version 2.6.
This is new as of Python 2.2, and, for example, is true of int.__add__. An object passing this test has a __get__ attribute but not a __set__ attribute, but beyond that the set of attributes varies. __name__ 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 im_func attribute (etc) when an object passes ismethod().
Return true if the object is a data descriptor.
Data descriptors have both a __get__ and a __set__ attribute. 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.
New in version 2.3.
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.
New in version 2.5.
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.
New in version 2.5.
Clean up indentation from docstrings that are indented to line up with blocks of code. Any whitespace that can be uniformly removed from the second line onwards is removed. Also, all tabs are expanded to spaces.
New in version 2.6.
Get the names and default values of a Python function’s arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). args is a list of the argument names (it may contain nested lists). varargs and varkw are the names of the * and ** arguments 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.
Changed in version 2.6: Returns a named tuple ArgSpec(args, varargs, keywords, defaults).
Get information about arguments passed into a particular frame. A tuple of four things is returned: (args, varargs, varkw, locals). args is a list of the argument names (it may contain nested lists). varargs and varkw are the names of the * and ** arguments or None. locals is the locals dictionary of the given frame.
Changed in version 2.6: Returns a named tuple ArgInfo(args, varargs, keywords, locals).
When the following functions return “frame records,” each record is a tuple of six items: 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.
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:
def handle_stackframe_without_leak(): frame = inspect.currentframe() try: # do something with the frame finally: del frame
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 5-tuple is returned, the last five elements of the frame’s frame record.
Changed in version 2.6: Returns a named tuple Traceback(filename, lineno, function, code_context, index).
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.