Python: module inspect (original) (raw)

Get useful information from live Python objects.

This module encapsulates the interface provided by the internal special
attributes (func_*, co_*, im_*, tb_*, etc.) in a friendlier fashion.
It also provides some help for examining source code and class layout.

Here are some of the useful functions provided by this module:

ismodule(), isclass(), ismethod(), isfunction(), istraceback(),
isframe(), iscode(), isbuiltin(), isroutine() - check object types
getmembers() - get members of an object that satisfy a given condition

getfile(), getsourcefile(), getsource() - find an object's source code
getdoc(), getcomments() - get documentation on an object
getmodule() - determine the module that an object came from
getclasstree() - arrange classes so as to represent their hierarchy

getargspec(), getargvalues() - get info about function arguments
formatargspec(), formatargvalues() - format an argument spec
getouterframes(), getinnerframes() - get info about frames
currentframe() - get the current stack frame
stack(), trace() - get info about frames on the stack or in a traceback

| | Functions | | | | | | ---------------- | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | | | | _getframe(...) _getframe([depth]) -> frameobject Return a frame object from the call stack. If optional integer depth isgiven, return the frame object that many calls below the top of the stack.If that is deeper than the call stack, ValueError is raised. The defaultfor depth is zero, returning the frame at the top of the call stack. This function should be used for internal and specializedpurposes only.findsource(object) Return the entire source file 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 all the linesin the file and the line number indexes a line in that list. An IOErroris raised if the source code cannot be retrieved.formatargspec(args, varargs=None, varkw=None, defaults=None, formatarg=, formatvarargs=<function >, formatvarkw=<function >, formatvalue=<function >, join=) Format an argument spec from the 4 values returned by getargspec. The first four arguments are (args, varargs, varkw, defaults). Theother four arguments are the corresponding optional formatting functionsthat are called to turn names and values into strings. The ninthargument is an optional function to format the sequence of arguments.formatargvalues(args, varargs, varkw, locals, formatarg=, formatvarargs=<function >, formatvarkw=<function >, formatvalue=<function >, join=) Format an argument spec from the 4 values returned by getargvalues. The first four arguments are (args, varargs, varkw, locals). Thenext four arguments are the corresponding optional formatting functionsthat are called to turn names and values into strings. The ninthargument is an optional function to format the sequence of arguments.getabsfile(object) Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routinenormalizes the result as much as possible.getargs(co) Get information about the arguments accepted by a code object. Three things are returned: (args, varargs, varkw), where 'args' isa list of argument names (possibly containing nested lists), and'varargs' and 'varkw' are the names of the * and ** arguments or None.getargspec(func) Get the names and default values of a 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 an n-tuple of the default values of the last n arguments.getargvalues(frame) 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.getblock(lines) Extract the block of code at the top of the given list of lines.getclasstree(classes, unique=0) Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the classwhose entry immediately precedes the list. Each entry is a 2-tuplecontaining a class and a tuple of its base classes. If the 'unique'argument is true, exactly one entry appears in the returned structurefor each class in the given list. Otherwise, classes using multipleinheritance and their descendants will appear multiple times.getcomments(object) Get lines of comments immediately preceding an object's source code.getdoc(object) Get the documentation string for an object. All tabs are expanded to spaces. To clean up docstrings that areindented to line up with blocks of code, any whitespace than can beuniformly removed from the second line onwards is removed.getfile(object) Work out which source or compiled file an object was defined in.getframeinfo(frame, context=1) Get information about a frame or traceback object. A tuple of five things is returned: the filename, the line number ofthe current line, the function name, a list of lines of context fromthe source code, and the index of the current line within that list.The optional second argument specifies the number of lines of contextto return, which are centered around the current line.getinnerframes(tb, context=1) Get a list of records for a traceback's frame and all lower frames. Each record contains a frame object, filename, line number, functionname, a list of lines of context, and index within the context.getlineno(frame) Get the line number from a frame object, allowing for optimization.getmembers(object, predicate=None) Return all members of an object as (name, value) pairs sorted by name.Optionally, only return members that satisfy a given predicate.getmodule(object) Return the module an object was defined in, or None if not found.getouterframes(frame, context=1) Get a list of records for a frame and all higher (calling) frames. Each record contains a frame object, filename, line number, functionname, a list of lines of context, and index within the context.getsource(object) 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. AnIOError is raised if the source code cannot be retrieved.getsourcefile(object) Return the Python source file an object was defined in, if it exists.getsourcelines(object) 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 linescorresponding to the object and the line number indicates where in theoriginal source file the first line of code was found. An IOError israised if the source code cannot be retrieved.indentsize(line) Return the indent size, in spaces, at the start of a line of text.isbuiltin(object) Return true if the object is a built-in function or method. Built-in functions and methods provide these attributes: __doc__ documentation string __name__ original name of this function or method __self__ instance to which a method is bound, or Noneisclass(object) Return true if the object is a class. Class objects provide these attributes: __doc__ documentation string __module__ name of module in which this class was definediscode(object) Return true if the object is a code object. Code objects provide these attributes: 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 variablesisframe(object) Return true if the object is a frame object. Frame objects provide these attributes: f_back next outer frame object (this frame's caller) f_builtins built-in 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 Noneisfunction(object) Return true if the object is a user-defined function. Function objects provide these attributes: __doc__ documentation string __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__)ismethod(object) Return true if the object is an instance method. Instance method objects provide these attributes: __doc__ documentation string __name__ name with which this method was defined im_class class object in which this method belongs im_func function object containing implementation of method im_self instance to which this method is bound, or Noneismodule(object) Return true if the object is a module. Module objects provide these attributes: __doc__ documentation string __file__ filename (missing for built-in modules)isroutine(object) Return true if the object is any kind of function or method.istraceback(object) Return true if the object is a traceback. Traceback objects provide these attributes: 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)joinseq(seq) stack(context=1) Return a list of records for the stack above the caller's frame.strseq(object, convert, join=) Recursively walk a sequence, stringifying each element.trace(context=1) Return a list of records for the stack below the current exception.walktree(classes, children, parent) Recursive helper function for getclasstree(). |

| | Constants | | | | ---------------- | | ---------------------------------------------------------------------------------------- | | | | | CO_NEWLOCALS = 2CO_OPTIMIZED = 1CO_VARARGS = 4CO_VARKEYWORDS = 8 |

| | Author | | | | ------------- | | -------------------------- | | | | | Ka-Ping Yee ping@lfw.org |