mirror of
				https://github.com/python/cpython.git
				synced 2025-11-04 07:31:38 +00:00 
			
		
		
		
	
		
			
				
	
	
		
			365 lines
		
	
	
	
		
			15 KiB
		
	
	
	
		
			TeX
		
	
	
	
	
	
			
		
		
	
	
			365 lines
		
	
	
	
		
			15 KiB
		
	
	
	
		
			TeX
		
	
	
	
	
	
\section{\module{inspect} ---
 | 
						|
         Inspect live objects}
 | 
						|
 | 
						|
\declaremodule{standard}{inspect}
 | 
						|
\modulesynopsis{Extract information and source code from live objects.}
 | 
						|
\moduleauthor{Ka-Ping Yee}{ping@lfw.org}
 | 
						|
\sectionauthor{Ka-Ping Yee}{ping@lfw.org}
 | 
						|
 | 
						|
\versionadded{2.1}
 | 
						|
 | 
						|
The \module{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.
 | 
						|
 | 
						|
\subsection{Types and members
 | 
						|
            \label{inspect-types}}
 | 
						|
 | 
						|
The \function{getmembers()} function retrieves the members
 | 
						|
of an object such as a class or module.
 | 
						|
The nine functions whose names begin with ``is'' are mainly
 | 
						|
provided as convenient choices for the second argument to
 | 
						|
\function{getmembers()}.  They also help you determine when
 | 
						|
you can expect to find the following special attributes:
 | 
						|
 | 
						|
\begin{tableiv}{c|l|l|c}{}{Type}{Attribute}{Description}{Notes}
 | 
						|
  \lineiv{module}{__doc__}{documentation string}{}
 | 
						|
  \lineiv{}{__file__}{filename (missing for built-in modules)}{}
 | 
						|
  \hline
 | 
						|
  \lineiv{class}{__doc__}{documentation string}{}
 | 
						|
  \lineiv{}{__module__}{name of module in which this class was defined}{}
 | 
						|
  \hline
 | 
						|
  \lineiv{method}{__doc__}{documentation string}{}
 | 
						|
  \lineiv{}{__name__}{name with which this method was defined}{}
 | 
						|
  \lineiv{}{im_class}{class object that asked for this method}{(1)}
 | 
						|
  \lineiv{}{im_func}{function object containing implementation of method}{}
 | 
						|
  \lineiv{}{im_self}{instance to which this method is bound, or \code{None}}{}
 | 
						|
  \hline
 | 
						|
  \lineiv{function}{__doc__}{documentation string}{}
 | 
						|
  \lineiv{}{__name__}{name with which this function was defined}{}
 | 
						|
  \lineiv{}{func_code}{code object containing compiled function bytecode}{}
 | 
						|
  \lineiv{}{func_defaults}{tuple of any default values for arguments}{}
 | 
						|
  \lineiv{}{func_doc}{(same as __doc__)}{}
 | 
						|
  \lineiv{}{func_globals}{global namespace in which this function was defined}{}
 | 
						|
  \lineiv{}{func_name}{(same as __name__)}{}
 | 
						|
  \hline
 | 
						|
  \lineiv{traceback}{tb_frame}{frame object at this level}{}
 | 
						|
  \lineiv{}{tb_lasti}{index of last attempted instruction in bytecode}{}
 | 
						|
  \lineiv{}{tb_lineno}{current line number in Python source code}{}
 | 
						|
  \lineiv{}{tb_next}{next inner traceback object (called by this level)}{}
 | 
						|
  \hline
 | 
						|
  \lineiv{frame}{f_back}{next outer frame object (this frame's caller)}{}
 | 
						|
  \lineiv{}{f_builtins}{built-in namespace seen by this frame}{}
 | 
						|
  \lineiv{}{f_code}{code object being executed in this frame}{}
 | 
						|
  \lineiv{}{f_exc_traceback}{traceback if raised in this frame, or \code{None}}{}
 | 
						|
  \lineiv{}{f_exc_type}{exception type if raised in this frame, or \code{None}}{}
 | 
						|
  \lineiv{}{f_exc_value}{exception value if raised in this frame, or \code{None}}{}
 | 
						|
  \lineiv{}{f_globals}{global namespace seen by this frame}{}
 | 
						|
  \lineiv{}{f_lasti}{index of last attempted instruction in bytecode}{}
 | 
						|
  \lineiv{}{f_lineno}{current line number in Python source code}{}
 | 
						|
  \lineiv{}{f_locals}{local namespace seen by this frame}{}
 | 
						|
  \lineiv{}{f_restricted}{0 or 1 if frame is in restricted execution mode}{}
 | 
						|
  \lineiv{}{f_trace}{tracing function for this frame, or \code{None}}{}
 | 
						|
  \hline
 | 
						|
  \lineiv{code}{co_argcount}{number of arguments (not including * or ** args)}{}
 | 
						|
  \lineiv{}{co_code}{string of raw compiled bytecode}{}
 | 
						|
  \lineiv{}{co_consts}{tuple of constants used in the bytecode}{}
 | 
						|
  \lineiv{}{co_filename}{name of file in which this code object was created}{}
 | 
						|
  \lineiv{}{co_firstlineno}{number of first line in Python source code}{}
 | 
						|
  \lineiv{}{co_flags}{bitmap: 1=optimized \code{|} 2=newlocals \code{|} 4=*arg \code{|} 8=**arg}{}
 | 
						|
  \lineiv{}{co_lnotab}{encoded mapping of line numbers to bytecode indices}{}
 | 
						|
  \lineiv{}{co_name}{name with which this code object was defined}{}
 | 
						|
  \lineiv{}{co_names}{tuple of names of local variables}{}
 | 
						|
  \lineiv{}{co_nlocals}{number of local variables}{}
 | 
						|
  \lineiv{}{co_stacksize}{virtual machine stack space required}{}
 | 
						|
  \lineiv{}{co_varnames}{tuple of names of arguments and local variables}{}
 | 
						|
  \hline
 | 
						|
  \lineiv{builtin}{__doc__}{documentation string}{}
 | 
						|
  \lineiv{}{__name__}{original name of this function or method}{}
 | 
						|
  \lineiv{}{__self__}{instance to which a method is bound, or \code{None}}{}
 | 
						|
\end{tableiv}
 | 
						|
 | 
						|
\noindent
 | 
						|
Note:
 | 
						|
\begin{description}
 | 
						|
\item[(1)]
 | 
						|
\versionchanged[\member{im_class} used to refer to the class that
 | 
						|
                defined the method]{2.2}
 | 
						|
\end{description}
 | 
						|
 | 
						|
 | 
						|
\begin{funcdesc}{getmembers}{object\optional{, predicate}}
 | 
						|
  Return all the members of an object in a list of (name, value) pairs
 | 
						|
  sorted by name.  If the optional \var{predicate} argument is supplied,
 | 
						|
  only members for which the predicate returns a true value are included.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{getmoduleinfo}{path}
 | 
						|
  Return a tuple of values that describe how Python will interpret the
 | 
						|
  file identified by \var{path} if it is a module, or \code{None} if
 | 
						|
  it would not be identified as a module.  The return tuple is
 | 
						|
  \code{(\var{name}, \var{suffix}, \var{mode}, \var{mtype})}, where
 | 
						|
  \var{name} is the name of the module without the name of any
 | 
						|
  enclosing package, \var{suffix} is the trailing part of the file
 | 
						|
  name (which may not be a dot-delimited extension), \var{mode} is the
 | 
						|
  \function{open()} mode that would be used (\code{'r'} or
 | 
						|
  \code{'rb'}), and \var{mtype} is an integer giving the type of the
 | 
						|
  module.  \var{mtype} will have a value which can be compared to the
 | 
						|
  constants defined in the \refmodule{imp} module; see the
 | 
						|
  documentation for that module for more information on module types.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{getmodulename}{path}
 | 
						|
  Return the name of the module named by the file \var{path}, without
 | 
						|
  including the names of enclosing packages.  This uses the same
 | 
						|
  algortihm as the interpreter uses when searching for modules.  If
 | 
						|
  the name cannot be matched according to the interpreter's rules,
 | 
						|
  \code{None} is returned.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{ismodule}{object}
 | 
						|
  Return true if the object is a module.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{isclass}{object}
 | 
						|
  Return true if the object is a class.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{ismethod}{object}
 | 
						|
  Return true if the object is a method.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{isfunction}{object}
 | 
						|
  Return true if the object is a Python function or unnamed (lambda) function.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{istraceback}{object}
 | 
						|
  Return true if the object is a traceback.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{isframe}{object}
 | 
						|
  Return true if the object is a frame.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{iscode}{object}
 | 
						|
  Return true if the object is a code.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{isbuiltin}{object}
 | 
						|
  Return true if the object is a built-in function.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{isroutine}{object}
 | 
						|
  Return true if the object is a user-defined or built-in function or method.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{ismethoddescriptor}{object}
 | 
						|
  Return true if the object is a method descriptor, but not if ismethod() or 
 | 
						|
  isclass() or isfunction() are true.
 | 
						|
 | 
						|
  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().
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{isdatadescriptor}{object}
 | 
						|
  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) and getsets and members (defined in C).
 | 
						|
  Typically, data descriptors will also have __name__ and __doc__ attributes 
 | 
						|
  (properties, getsets, and members have both of these attributes), but this 
 | 
						|
  is not guaranteed.
 | 
						|
\versionadded{2.3}
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\subsection{Retrieving source code
 | 
						|
            \label{inspect-source}}
 | 
						|
 | 
						|
\begin{funcdesc}{getdoc}{object}
 | 
						|
  Get the documentation string for an object.
 | 
						|
  All tabs are expanded to spaces.  To clean up docstrings that are
 | 
						|
  indented to line up with blocks of code, any whitespace than can be
 | 
						|
  uniformly removed from the second line onwards is removed.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{getcomments}{object}
 | 
						|
  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).
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{getfile}{object}
 | 
						|
  Return the name of the (text or binary) file in which an object was
 | 
						|
  defined.  This will fail with a \exception{TypeError} if the object
 | 
						|
  is a built-in module, class, or function.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{getmodule}{object}
 | 
						|
  Try to guess which module an object was defined in.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{getsourcefile}{object}
 | 
						|
  Return the name of the Python source file in which an object was
 | 
						|
  defined.  This will fail with a \exception{TypeError} if the object
 | 
						|
  is a built-in module, class, or function.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{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 lines
 | 
						|
  corresponding to the object and the line number indicates where in the
 | 
						|
  original source file the first line of code was found.  An
 | 
						|
  \exception{IOError} is raised if the source code cannot be retrieved.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{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.  An
 | 
						|
  \exception{IOError} is raised if the source code cannot be retrieved.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\subsection{Classes and functions
 | 
						|
            \label{inspect-classes-functions}}
 | 
						|
 | 
						|
\begin{funcdesc}{getclasstree}{classes\optional{, unique}}
 | 
						|
  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 \var{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.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{getargspec}{func}
 | 
						|
  Get the names and default values of a function's arguments.
 | 
						|
  A tuple of four things is returned: \code{(\var{args},
 | 
						|
    \var{varargs}, \var{varkw}, \var{defaults})}.
 | 
						|
  \var{args} is a list of the argument names (it may contain nested lists).
 | 
						|
  \var{varargs} and \var{varkw} are the names of the \code{*} and
 | 
						|
  \code{**} arguments or \code{None}.
 | 
						|
  \var{defaults} is a tuple of default argument values; if this tuple
 | 
						|
  has \var{n} elements, they correspond to the last \var{n} elements
 | 
						|
  listed in \var{args}.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{getargvalues}{frame}
 | 
						|
  Get information about arguments passed into a particular frame.
 | 
						|
  A tuple of four things is returned: \code{(\var{args},
 | 
						|
    \var{varargs}, \var{varkw}, \var{locals})}.
 | 
						|
  \var{args} is a list of the argument names (it may contain nested
 | 
						|
  lists).
 | 
						|
  \var{varargs} and \var{varkw} are the names of the \code{*} and
 | 
						|
  \code{**} arguments or \code{None}.
 | 
						|
  \var{locals} is the locals dictionary of the given frame.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{formatargspec}{args\optional{, varargs, varkw, defaults,
 | 
						|
      argformat, varargsformat, varkwformat, defaultformat}}
 | 
						|
 | 
						|
  Format a pretty argument spec from the four values returned by
 | 
						|
  \function{getargspec()}.  The other four arguments are the
 | 
						|
  corresponding optional formatting functions that are called to turn
 | 
						|
  names and values into strings.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{formatargvalues}{args\optional{, varargs, varkw, locals,
 | 
						|
      argformat, varargsformat, varkwformat, valueformat}}
 | 
						|
  Format a pretty argument spec from the four values returned by
 | 
						|
  \function{getargvalues()}.  The other four arguments are the
 | 
						|
  corresponding optional formatting functions that are called to turn
 | 
						|
  names and values into strings.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{getmro}{cls}
 | 
						|
  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.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\subsection{The interpreter stack
 | 
						|
            \label{inspect-stack}}
 | 
						|
 | 
						|
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.
 | 
						|
The optional \var{context} argument specifies the number of lines of
 | 
						|
context to return, which are centered around the current line.
 | 
						|
 | 
						|
\warning{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.}
 | 
						|
 | 
						|
\begin{funcdesc}{getframeinfo}{frame\optional{, context}}
 | 
						|
  Get information about a frame or traceback object.  A 5-tuple
 | 
						|
  is returned, the last five elements of the frame's frame record.
 | 
						|
  The optional second argument specifies the number of lines of context
 | 
						|
  to return, which are centered around the current line.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{getouterframes}{frame\optional{, context}}
 | 
						|
  Get a list of frame records for a frame and all higher (calling)
 | 
						|
  frames.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{getinnerframes}{traceback\optional{, context}}
 | 
						|
  Get a list of frame records for a traceback's frame and all lower
 | 
						|
  frames.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{currentframe}{}
 | 
						|
  Return the frame object for the caller's stack frame.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{stack}{\optional{context}}
 | 
						|
  Return a list of frame records for the stack above the caller's
 | 
						|
  frame.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
\begin{funcdesc}{trace}{\optional{context}}
 | 
						|
  Return a list of frame records for the stack below the current
 | 
						|
  exception.
 | 
						|
\end{funcdesc}
 | 
						|
 | 
						|
Stackframes stored directly or indirectly in local variables can
 | 
						|
easily cause reference cycles.  Though the cycle detector will catch
 | 
						|
these, destruction of the frames (and local variables) can be made
 | 
						|
deterministic by removing the cycle in a \keyword{finally} clause.
 | 
						|
This is also important if the cycle detector was disabled when Python
 | 
						|
was compiled or using \function{gc.disable()}.  For example:
 | 
						|
 | 
						|
\begin{verbatim}
 | 
						|
def handle_stackframe_without_leak():
 | 
						|
    frame = inspect.currentframe()
 | 
						|
    try:
 | 
						|
        # do something with the frame
 | 
						|
    finally:
 | 
						|
        del frame
 | 
						|
\end{verbatim}
 |