- Got rid of newmodule.c
[python/dscho.git] / Doc / lib / libinspect.tex
bloba1293f0e96a8a055a8c2663531b023d12874e6a2
1 \section{\module{inspect} ---
2 Inspect live objects}
4 \declaremodule{standard}{inspect}
5 \modulesynopsis{Extract information and source code from live objects.}
6 \moduleauthor{Ka-Ping Yee}{ping@lfw.org}
7 \sectionauthor{Ka-Ping Yee}{ping@lfw.org}
9 \versionadded{2.1}
11 The \module{inspect} module provides several useful functions
12 to help get information about live objects such as modules,
13 classes, methods, functions, tracebacks, frame objects, and
14 code objects. For example, it can help you examine the
15 contents of a class, retrieve the source code of a method,
16 extract and format the argument list for a function, or
17 get all the information you need to display a detailed traceback.
19 There are four main kinds of services provided by this module:
20 type checking, getting source code, inspecting classes
21 and functions, and examining the interpreter stack.
23 \subsection{Types and members
24 \label{inspect-types}}
26 The \function{getmembers()} function retrieves the members
27 of an object such as a class or module.
28 The nine functions whose names begin with ``is'' are mainly
29 provided as convenient choices for the second argument to
30 \function{getmembers()}. They also help you determine when
31 you can expect to find the following special attributes:
33 \begin{tableiv}{c|l|l|c}{}{Type}{Attribute}{Description}{Notes}
34 \lineiv{module}{__doc__}{documentation string}{}
35 \lineiv{}{__file__}{filename (missing for built-in modules)}{}
36 \hline
37 \lineiv{class}{__doc__}{documentation string}{}
38 \lineiv{}{__module__}{name of module in which this class was defined}{}
39 \hline
40 \lineiv{method}{__doc__}{documentation string}{}
41 \lineiv{}{__name__}{name with which this method was defined}{}
42 \lineiv{}{im_class}{class object that asked for this method}{(1)}
43 \lineiv{}{im_func}{function object containing implementation of method}{}
44 \lineiv{}{im_self}{instance to which this method is bound, or \code{None}}{}
45 \hline
46 \lineiv{function}{__doc__}{documentation string}{}
47 \lineiv{}{__name__}{name with which this function was defined}{}
48 \lineiv{}{func_code}{code object containing compiled function bytecode}{}
49 \lineiv{}{func_defaults}{tuple of any default values for arguments}{}
50 \lineiv{}{func_doc}{(same as __doc__)}{}
51 \lineiv{}{func_globals}{global namespace in which this function was defined}{}
52 \lineiv{}{func_name}{(same as __name__)}{}
53 \hline
54 \lineiv{traceback}{tb_frame}{frame object at this level}{}
55 \lineiv{}{tb_lasti}{index of last attempted instruction in bytecode}{}
56 \lineiv{}{tb_lineno}{current line number in Python source code}{}
57 \lineiv{}{tb_next}{next inner traceback object (called by this level)}{}
58 \hline
59 \lineiv{frame}{f_back}{next outer frame object (this frame's caller)}{}
60 \lineiv{}{f_builtins}{built-in namespace seen by this frame}{}
61 \lineiv{}{f_code}{code object being executed in this frame}{}
62 \lineiv{}{f_exc_traceback}{traceback if raised in this frame, or \code{None}}{}
63 \lineiv{}{f_exc_type}{exception type if raised in this frame, or \code{None}}{}
64 \lineiv{}{f_exc_value}{exception value if raised in this frame, or \code{None}}{}
65 \lineiv{}{f_globals}{global namespace seen by this frame}{}
66 \lineiv{}{f_lasti}{index of last attempted instruction in bytecode}{}
67 \lineiv{}{f_lineno}{current line number in Python source code}{}
68 \lineiv{}{f_locals}{local namespace seen by this frame}{}
69 \lineiv{}{f_restricted}{0 or 1 if frame is in restricted execution mode}{}
70 \lineiv{}{f_trace}{tracing function for this frame, or \code{None}}{}
71 \hline
72 \lineiv{code}{co_argcount}{number of arguments (not including * or ** args)}{}
73 \lineiv{}{co_code}{string of raw compiled bytecode}{}
74 \lineiv{}{co_consts}{tuple of constants used in the bytecode}{}
75 \lineiv{}{co_filename}{name of file in which this code object was created}{}
76 \lineiv{}{co_firstlineno}{number of first line in Python source code}{}
77 \lineiv{}{co_flags}{bitmap: 1=optimized \code{|} 2=newlocals \code{|} 4=*arg \code{|} 8=**arg}{}
78 \lineiv{}{co_lnotab}{encoded mapping of line numbers to bytecode indices}{}
79 \lineiv{}{co_name}{name with which this code object was defined}{}
80 \lineiv{}{co_names}{tuple of names of local variables}{}
81 \lineiv{}{co_nlocals}{number of local variables}{}
82 \lineiv{}{co_stacksize}{virtual machine stack space required}{}
83 \lineiv{}{co_varnames}{tuple of names of arguments and local variables}{}
84 \hline
85 \lineiv{builtin}{__doc__}{documentation string}{}
86 \lineiv{}{__name__}{original name of this function or method}{}
87 \lineiv{}{__self__}{instance to which a method is bound, or \code{None}}{}
88 \end{tableiv}
90 \noindent
91 Note:
92 \begin{description}
93 \item[(1)]
94 \versionchanged[\member{im_class} used to refer to the class that
95 defined the method]{2.2}
96 \end{description}
99 \begin{funcdesc}{getmembers}{object\optional{, predicate}}
100 Return all the members of an object in a list of (name, value) pairs
101 sorted by name. If the optional \var{predicate} argument is supplied,
102 only members for which the predicate returns a true value are included.
103 \end{funcdesc}
105 \begin{funcdesc}{getmoduleinfo}{path}
106 Return a tuple of values that describe how Python will interpret the
107 file identified by \var{path} if it is a module, or \code{None} if
108 it would not be identified as a module. The return tuple is
109 \code{(\var{name}, \var{suffix}, \var{mode}, \var{mtype})}, where
110 \var{name} is the name of the module without the name of any
111 enclosing package, \var{suffix} is the trailing part of the file
112 name (which may not be a dot-delimited extension), \var{mode} is the
113 \function{open()} mode that would be used (\code{'r'} or
114 \code{'rb'}), and \var{mtype} is an integer giving the type of the
115 module. \var{mtype} will have a value which can be compared to the
116 constants defined in the \refmodule{imp} module; see the
117 documentation for that module for more information on module types.
118 \end{funcdesc}
120 \begin{funcdesc}{getmodulename}{path}
121 Return the name of the module named by the file \var{path}, without
122 including the names of enclosing packages. This uses the same
123 algortihm as the interpreter uses when searching for modules. If
124 the name cannot be matched according to the interpreter's rules,
125 \code{None} is returned.
126 \end{funcdesc}
128 \begin{funcdesc}{ismodule}{object}
129 Return true if the object is a module.
130 \end{funcdesc}
132 \begin{funcdesc}{isclass}{object}
133 Return true if the object is a class.
134 \end{funcdesc}
136 \begin{funcdesc}{ismethod}{object}
137 Return true if the object is a method.
138 \end{funcdesc}
140 \begin{funcdesc}{isfunction}{object}
141 Return true if the object is a Python function or unnamed (lambda) function.
142 \end{funcdesc}
144 \begin{funcdesc}{istraceback}{object}
145 Return true if the object is a traceback.
146 \end{funcdesc}
148 \begin{funcdesc}{isframe}{object}
149 Return true if the object is a frame.
150 \end{funcdesc}
152 \begin{funcdesc}{iscode}{object}
153 Return true if the object is a code.
154 \end{funcdesc}
156 \begin{funcdesc}{isbuiltin}{object}
157 Return true if the object is a built-in function.
158 \end{funcdesc}
160 \begin{funcdesc}{isroutine}{object}
161 Return true if the object is a user-defined or built-in function or method.
162 \end{funcdesc}
164 \subsection{Retrieving source code
165 \label{inspect-source}}
167 \begin{funcdesc}{getdoc}{object}
168 Get the documentation string for an object.
169 All tabs are expanded to spaces. To clean up docstrings that are
170 indented to line up with blocks of code, any whitespace than can be
171 uniformly removed from the second line onwards is removed.
172 \end{funcdesc}
174 \begin{funcdesc}{getcomments}{object}
175 Return in a single string any lines of comments immediately preceding
176 the object's source code (for a class, function, or method), or at the
177 top of the Python source file (if the object is a module).
178 \end{funcdesc}
180 \begin{funcdesc}{getfile}{object}
181 Return the name of the (text or binary) file in which an object was
182 defined. This will fail with a \exception{TypeError} if the object
183 is a built-in module, class, or function.
184 \end{funcdesc}
186 \begin{funcdesc}{getmodule}{object}
187 Try to guess which module an object was defined in.
188 \end{funcdesc}
190 \begin{funcdesc}{getsourcefile}{object}
191 Return the name of the Python source file in which an object was
192 defined. This will fail with a \exception{TypeError} if the object
193 is a built-in module, class, or function.
194 \end{funcdesc}
196 \begin{funcdesc}{getsourcelines}{object}
197 Return a list of source lines and starting line number for an object.
198 The argument may be a module, class, method, function, traceback, frame,
199 or code object. The source code is returned as a list of the lines
200 corresponding to the object and the line number indicates where in the
201 original source file the first line of code was found. An
202 \exception{IOError} is raised if the source code cannot be retrieved.
203 \end{funcdesc}
205 \begin{funcdesc}{getsource}{object}
206 Return the text of the source code for an object.
207 The argument may be a module, class, method, function, traceback, frame,
208 or code object. The source code is returned as a single string. An
209 \exception{IOError} is raised if the source code cannot be retrieved.
210 \end{funcdesc}
212 \subsection{Classes and functions
213 \label{inspect-classes-functions}}
215 \begin{funcdesc}{getclasstree}{classes\optional{, unique}}
216 Arrange the given list of classes into a hierarchy of nested lists.
217 Where a nested list appears, it contains classes derived from the class
218 whose entry immediately precedes the list. Each entry is a 2-tuple
219 containing a class and a tuple of its base classes. If the \var{unique}
220 argument is true, exactly one entry appears in the returned structure
221 for each class in the given list. Otherwise, classes using multiple
222 inheritance and their descendants will appear multiple times.
223 \end{funcdesc}
225 \begin{funcdesc}{getargspec}{func}
226 Get the names and default values of a function's arguments.
227 A tuple of four things is returned: \code{(\var{args},
228 \var{varargs}, \var{varkw}, \var{defaults})}.
229 \var{args} is a list of the argument names (it may contain nested lists).
230 \var{varargs} and \var{varkw} are the names of the \code{*} and
231 \code{**} arguments or \code{None}.
232 \var{defaults} is a tuple of default argument values; if this tuple
233 has \var{n} elements, they correspond to the last \var{n} elements
234 listed in \var{args}.
235 \end{funcdesc}
237 \begin{funcdesc}{getargvalues}{frame}
238 Get information about arguments passed into a particular frame.
239 A tuple of four things is returned: \code{(\var{args},
240 \var{varargs}, \var{varkw}, \var{locals})}.
241 \var{args} is a list of the argument names (it may contain nested
242 lists).
243 \var{varargs} and \var{varkw} are the names of the \code{*} and
244 \code{**} arguments or \code{None}.
245 \var{locals} is the locals dictionary of the given frame.
246 \end{funcdesc}
248 \begin{funcdesc}{formatargspec}{args\optional{, varargs, varkw, defaults,
249 argformat, varargsformat, varkwformat, defaultformat}}
251 Format a pretty argument spec from the four values returned by
252 \function{getargspec()}. The other four arguments are the
253 corresponding optional formatting functions that are called to turn
254 names and values into strings.
255 \end{funcdesc}
257 \begin{funcdesc}{formatargvalues}{args\optional{, varargs, varkw, locals,
258 argformat, varargsformat, varkwformat, valueformat}}
259 Format a pretty argument spec from the four values returned by
260 \function{getargvalues()}. The other four arguments are the
261 corresponding optional formatting functions that are called to turn
262 names and values into strings.
263 \end{funcdesc}
265 \begin{funcdesc}{getmro}{cls}
266 Return a tuple of class cls's base classes, including cls, in
267 method resolution order. No class appears more than once in this tuple.
268 Note that the method resolution order depends on cls's type. Unless a
269 very peculiar user-defined metatype is in use, cls will be the first
270 element of the tuple.
271 \end{funcdesc}
273 \subsection{The interpreter stack
274 \label{inspect-stack}}
276 When the following functions return ``frame records,'' each record
277 is a tuple of six items: the frame object, the filename,
278 the line number of the current line, the function name, a list of
279 lines of context from the source code, and the index of the current
280 line within that list.
281 The optional \var{context} argument specifies the number of lines of
282 context to return, which are centered around the current line.
284 \warning{Keeping references to frame objects, as found in
285 the first element of the frame records these functions return, can
286 cause your program to create reference cycles. Once a reference cycle
287 has been created, the lifespan of all objects which can be accessed
288 from the objects which form the cycle can become much longer even if
289 Python's optional cycle detector is enabled. If such cycles must be
290 created, it is important to ensure they are explicitly broken to avoid
291 the delayed destruction of objects and increased memory consumption
292 which occurs.}
294 \begin{funcdesc}{getframeinfo}{frame\optional{, context}}
295 Get information about a frame or traceback object. A 5-tuple
296 is returned, the last five elements of the frame's frame record.
297 The optional second argument specifies the number of lines of context
298 to return, which are centered around the current line.
299 \end{funcdesc}
301 \begin{funcdesc}{getouterframes}{frame\optional{, context}}
302 Get a list of frame records for a frame and all higher (calling)
303 frames.
304 \end{funcdesc}
306 \begin{funcdesc}{getinnerframes}{traceback\optional{, context}}
307 Get a list of frame records for a traceback's frame and all lower
308 frames.
309 \end{funcdesc}
311 \begin{funcdesc}{currentframe}{}
312 Return the frame object for the caller's stack frame.
313 \end{funcdesc}
315 \begin{funcdesc}{stack}{\optional{context}}
316 Return a list of frame records for the stack above the caller's
317 frame.
318 \end{funcdesc}
320 \begin{funcdesc}{trace}{\optional{context}}
321 Return a list of frame records for the stack below the current
322 exception.
323 \end{funcdesc}
325 Stackframes stored directly or indirectly in local variables can
326 easily cause reference cycles. Though the cycle detector will catch
327 these, destruction of the frames (and local variables) can be made
328 deterministic by removing the cycle in a \keyword{finally} clause.
329 This is also important if the cycle detector was disabled when Python
330 was compiled or using \function{gc.disable()}. For example:
332 \begin{verbatim}
333 def handle_stackframe_without_leak():
334 frame = inspect.currentframe()
335 try:
336 # do something with the frame
337 finally:
338 del frame
339 \end{verbatim}