blob: 85651f0609c20cbce108376a69d26565b4f8811c [file] [log] [blame]
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00001\section{\module{inspect} ---
2 Inspect live objects}
Fred Drake6dbd3822001-02-28 23:01:38 +00003
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00004\declaremodule{standard}{inspect}
5\modulesynopsis{Extract information and source code from live objects.}
Fred Drake6dbd3822001-02-28 23:01:38 +00006\moduleauthor{Ka-Ping Yee}{ping@lfw.org}
7\sectionauthor{Ka-Ping Yee}{ping@lfw.org}
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +00008
9\versionadded{2.1}
10
Fred Drake6dbd3822001-02-28 23:01:38 +000011The \module{inspect} module provides several useful functions
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000012to help get information about live objects such as modules,
13classes, methods, functions, tracebacks, frame objects, and
14code objects. For example, it can help you examine the
15contents of a class, retrieve the source code of a method,
16extract and format the argument list for a function, or
17get all the information you need to display a detailed traceback.
18
19There are four main kinds of services provided by this module:
20type checking, getting source code, inspecting classes
21and functions, and examining the interpreter stack.
22
23\subsection{Types and members
24 \label{inspect-types}}
25
26The \function{getmembers()} function retrieves the members
27of an object such as a class or module.
Martin v. Löwis893ffa42003-10-31 15:35:53 +000028The eleven functions whose names begin with ``is'' are mainly
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000029provided as convenient choices for the second argument to
30\function{getmembers()}. They also help you determine when
31you can expect to find the following special attributes:
32
Fred Drakef9d58032001-12-07 23:13:53 +000033\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)}{}
Fred Drake6dbd3822001-02-28 23:01:38 +000036 \hline
Fred Drakef9d58032001-12-07 23:13:53 +000037 \lineiv{class}{__doc__}{documentation string}{}
38 \lineiv{}{__module__}{name of module in which this class was defined}{}
Fred Drake6dbd3822001-02-28 23:01:38 +000039 \hline
Fred Drakef9d58032001-12-07 23:13:53 +000040 \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}}{}
Fred Drake6dbd3822001-02-28 23:01:38 +000045 \hline
Fred Drakef9d58032001-12-07 23:13:53 +000046 \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__)}{}
Fred Drake6dbd3822001-02-28 23:01:38 +000053 \hline
Fred Drakef9d58032001-12-07 23:13:53 +000054 \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)}{}
Fred Drake6dbd3822001-02-28 23:01:38 +000058 \hline
Fred Drakef9d58032001-12-07 23:13:53 +000059 \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}}{}
Fred Drake6dbd3822001-02-28 23:01:38 +000071 \hline
Fred Drakef9d58032001-12-07 23:13:53 +000072 \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}{}
Fred Drake6dbd3822001-02-28 23:01:38 +000084 \hline
Fred Drakef9d58032001-12-07 23:13:53 +000085 \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}
89
90\noindent
91Note:
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}
97
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000098
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}
104
Fred Drake90a72f82001-04-10 15:12:34 +0000105\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}
119
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
Fred Drakebb066cf2004-05-12 03:07:27 +0000123 algorithm as the interpreter uses when searching for modules. If
Fred Drake90a72f82001-04-10 15:12:34 +0000124 the name cannot be matched according to the interpreter's rules,
125 \code{None} is returned.
126\end{funcdesc}
127
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000128\begin{funcdesc}{ismodule}{object}
129 Return true if the object is a module.
130\end{funcdesc}
131
132\begin{funcdesc}{isclass}{object}
133 Return true if the object is a class.
134\end{funcdesc}
135
136\begin{funcdesc}{ismethod}{object}
137 Return true if the object is a method.
138\end{funcdesc}
139
140\begin{funcdesc}{isfunction}{object}
141 Return true if the object is a Python function or unnamed (lambda) function.
142\end{funcdesc}
143
144\begin{funcdesc}{istraceback}{object}
145 Return true if the object is a traceback.
146\end{funcdesc}
147
148\begin{funcdesc}{isframe}{object}
149 Return true if the object is a frame.
150\end{funcdesc}
151
152\begin{funcdesc}{iscode}{object}
153 Return true if the object is a code.
154\end{funcdesc}
155
156\begin{funcdesc}{isbuiltin}{object}
157 Return true if the object is a built-in function.
158\end{funcdesc}
159
160\begin{funcdesc}{isroutine}{object}
161 Return true if the object is a user-defined or built-in function or method.
162\end{funcdesc}
163
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000164\begin{funcdesc}{ismethoddescriptor}{object}
165 Return true if the object is a method descriptor, but not if ismethod() or
166 isclass() or isfunction() are true.
167
168 This is new as of Python 2.2, and, for example, is true of int.__add__.
169 An object passing this test has a __get__ attribute but not a __set__
170 attribute, but beyond that the set of attributes varies. __name__ is
171 usually sensible, and __doc__ often is.
172
173 Methods implemented via descriptors that also pass one of the other
174 tests return false from the ismethoddescriptor() test, simply because
175 the other tests promise more -- you can, e.g., count on having the
176 im_func attribute (etc) when an object passes ismethod().
177\end{funcdesc}
178
179\begin{funcdesc}{isdatadescriptor}{object}
180 Return true if the object is a data descriptor.
181
182 Data descriptors have both a __get__ and a __set__ attribute. Examples are
Barry Warsaw00decd72006-07-27 23:43:15 +0000183 properties (defined in Python), getsets, and members. The latter two are
184 defined in C and there are more specific tests available for those types,
185 which is robust across Python implementations. Typically, data descriptors
186 will also have __name__ and __doc__ attributes (properties, getsets, and
187 members have both of these attributes), but this is not guaranteed.
Neal Norwitzd3d57682003-05-29 02:10:31 +0000188\versionadded{2.3}
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000189\end{funcdesc}
190
Barry Warsaw00decd72006-07-27 23:43:15 +0000191\begin{funcdesc}{isgetsetdescriptor}{object}
192 Return true if the object is a getset descriptor.
193
194 getsets are attributes defined in extension modules via \code{PyGetSetDef}
195 structures. For Python implementations without such types, this method will
196 always return \code{False}.
197\versionadded{2.5}
198\end{funcdesc}
199
200\begin{funcdesc}{ismemberdescriptor}{object}
201 Return true if the object is a member descriptor.
202
203 Member descriptors are attributes defined in extension modules via
204 \code{PyMemberDef} structures. For Python implementations without such
205 types, this method will always return \code{False}.
206\versionadded{2.5}
207\end{funcdesc}
208
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000209\subsection{Retrieving source code
210 \label{inspect-source}}
211
212\begin{funcdesc}{getdoc}{object}
213 Get the documentation string for an object.
214 All tabs are expanded to spaces. To clean up docstrings that are
215 indented to line up with blocks of code, any whitespace than can be
216 uniformly removed from the second line onwards is removed.
217\end{funcdesc}
218
219\begin{funcdesc}{getcomments}{object}
220 Return in a single string any lines of comments immediately preceding
221 the object's source code (for a class, function, or method), or at the
222 top of the Python source file (if the object is a module).
223\end{funcdesc}
224
225\begin{funcdesc}{getfile}{object}
Fred Drake6dbd3822001-02-28 23:01:38 +0000226 Return the name of the (text or binary) file in which an object was
227 defined. This will fail with a \exception{TypeError} if the object
228 is a built-in module, class, or function.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000229\end{funcdesc}
230
231\begin{funcdesc}{getmodule}{object}
232 Try to guess which module an object was defined in.
233\end{funcdesc}
234
235\begin{funcdesc}{getsourcefile}{object}
Fred Drake6dbd3822001-02-28 23:01:38 +0000236 Return the name of the Python source file in which an object was
237 defined. This will fail with a \exception{TypeError} if the object
238 is a built-in module, class, or function.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000239\end{funcdesc}
240
241\begin{funcdesc}{getsourcelines}{object}
242 Return a list of source lines and starting line number for an object.
243 The argument may be a module, class, method, function, traceback, frame,
244 or code object. The source code is returned as a list of the lines
245 corresponding to the object and the line number indicates where in the
Fred Drake6dbd3822001-02-28 23:01:38 +0000246 original source file the first line of code was found. An
247 \exception{IOError} is raised if the source code cannot be retrieved.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000248\end{funcdesc}
249
250\begin{funcdesc}{getsource}{object}
251 Return the text of the source code for an object.
252 The argument may be a module, class, method, function, traceback, frame,
253 or code object. The source code is returned as a single string. An
Fred Drake6dbd3822001-02-28 23:01:38 +0000254 \exception{IOError} is raised if the source code cannot be retrieved.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000255\end{funcdesc}
256
257\subsection{Classes and functions
258 \label{inspect-classes-functions}}
259
260\begin{funcdesc}{getclasstree}{classes\optional{, unique}}
261 Arrange the given list of classes into a hierarchy of nested lists.
262 Where a nested list appears, it contains classes derived from the class
263 whose entry immediately precedes the list. Each entry is a 2-tuple
264 containing a class and a tuple of its base classes. If the \var{unique}
265 argument is true, exactly one entry appears in the returned structure
266 for each class in the given list. Otherwise, classes using multiple
267 inheritance and their descendants will appear multiple times.
268\end{funcdesc}
269
270\begin{funcdesc}{getargspec}{func}
271 Get the names and default values of a function's arguments.
Fred Drake6dbd3822001-02-28 23:01:38 +0000272 A tuple of four things is returned: \code{(\var{args},
273 \var{varargs}, \var{varkw}, \var{defaults})}.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000274 \var{args} is a list of the argument names (it may contain nested lists).
Fred Drake6dbd3822001-02-28 23:01:38 +0000275 \var{varargs} and \var{varkw} are the names of the \code{*} and
276 \code{**} arguments or \code{None}.
Brett Cannon91cc5cd2004-07-10 21:13:06 +0000277 \var{defaults} is a tuple of default argument values or None if there are no
278 default arguments; if this tuple has \var{n} elements, they correspond to
279 the last \var{n} elements listed in \var{args}.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000280\end{funcdesc}
281
282\begin{funcdesc}{getargvalues}{frame}
283 Get information about arguments passed into a particular frame.
Fred Drake6dbd3822001-02-28 23:01:38 +0000284 A tuple of four things is returned: \code{(\var{args},
285 \var{varargs}, \var{varkw}, \var{locals})}.
286 \var{args} is a list of the argument names (it may contain nested
287 lists).
288 \var{varargs} and \var{varkw} are the names of the \code{*} and
289 \code{**} arguments or \code{None}.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000290 \var{locals} is the locals dictionary of the given frame.
291\end{funcdesc}
292
293\begin{funcdesc}{formatargspec}{args\optional{, varargs, varkw, defaults,
Gregory P. Smithd856ce02006-08-04 05:17:47 +0000294 formatarg, formatvarargs, formatvarkw, formatvalue, join}}
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000295
Fred Drake6dbd3822001-02-28 23:01:38 +0000296 Format a pretty argument spec from the four values returned by
Gregory P. Smithd856ce02006-08-04 05:17:47 +0000297 \function{getargspec()}. The format* arguments are the
Fred Drake6dbd3822001-02-28 23:01:38 +0000298 corresponding optional formatting functions that are called to turn
299 names and values into strings.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000300\end{funcdesc}
301
302\begin{funcdesc}{formatargvalues}{args\optional{, varargs, varkw, locals,
Gregory P. Smithd856ce02006-08-04 05:17:47 +0000303 formatarg, formatvarargs, formatvarkw, formatvalue, join}}
Fred Drake6dbd3822001-02-28 23:01:38 +0000304 Format a pretty argument spec from the four values returned by
Gregory P. Smithd856ce02006-08-04 05:17:47 +0000305 \function{getargvalues()}. The format* arguments are the
Fred Drake6dbd3822001-02-28 23:01:38 +0000306 corresponding optional formatting functions that are called to turn
307 names and values into strings.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000308\end{funcdesc}
309
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000310\begin{funcdesc}{getmro}{cls}
311 Return a tuple of class cls's base classes, including cls, in
312 method resolution order. No class appears more than once in this tuple.
313 Note that the method resolution order depends on cls's type. Unless a
314 very peculiar user-defined metatype is in use, cls will be the first
315 element of the tuple.
316\end{funcdesc}
317
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000318\subsection{The interpreter stack
319 \label{inspect-stack}}
320
Fred Drake6dbd3822001-02-28 23:01:38 +0000321When the following functions return ``frame records,'' each record
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000322is a tuple of six items: the frame object, the filename,
323the line number of the current line, the function name, a list of
324lines of context from the source code, and the index of the current
325line within that list.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000326
Fred Drake6237ef12004-01-01 07:21:14 +0000327\begin{notice}[warning]
328Keeping references to frame objects, as found in
Fred Draked635e3c2001-08-10 17:37:33 +0000329the first element of the frame records these functions return, can
330cause your program to create reference cycles. Once a reference cycle
331has been created, the lifespan of all objects which can be accessed
332from the objects which form the cycle can become much longer even if
333Python's optional cycle detector is enabled. If such cycles must be
334created, it is important to ensure they are explicitly broken to avoid
335the delayed destruction of objects and increased memory consumption
Fred Drake6237ef12004-01-01 07:21:14 +0000336which occurs.
Fred Draked635e3c2001-08-10 17:37:33 +0000337
Fred Drake6237ef12004-01-01 07:21:14 +0000338Though the cycle detector will catch these, destruction of the frames
339(and local variables) can be made deterministic by removing the cycle
340in a \keyword{finally} clause. This is also important if the cycle
341detector was disabled when Python was compiled or using
342\function{\refmodule{gc}.disable()}. For example:
Fred Drake99d170062002-04-23 21:21:20 +0000343
344\begin{verbatim}
345def handle_stackframe_without_leak():
346 frame = inspect.currentframe()
347 try:
348 # do something with the frame
349 finally:
350 del frame
351\end{verbatim}
Fred Drake6237ef12004-01-01 07:21:14 +0000352\end{notice}
353
354The optional \var{context} argument supported by most of these
355functions specifies the number of lines of context to return, which
356are centered around the current line.
357
358\begin{funcdesc}{getframeinfo}{frame\optional{, context}}
359 Get information about a frame or traceback object. A 5-tuple
360 is returned, the last five elements of the frame's frame record.
361\end{funcdesc}
362
363\begin{funcdesc}{getouterframes}{frame\optional{, context}}
364 Get a list of frame records for a frame and all outer frames. These
365 frames represent the calls that lead to the creation of \var{frame}.
366 The first entry in the returned list represents \var{frame}; the
367 last entry represents the outermost call on \var{frame}'s stack.
368\end{funcdesc}
369
370\begin{funcdesc}{getinnerframes}{traceback\optional{, context}}
371 Get a list of frame records for a traceback's frame and all inner
372 frames. These frames represent calls made as a consequence of
373 \var{frame}. The first entry in the list represents
374 \var{traceback}; the last entry represents where the exception was
375 raised.
376\end{funcdesc}
377
378\begin{funcdesc}{currentframe}{}
379 Return the frame object for the caller's stack frame.
380\end{funcdesc}
381
382\begin{funcdesc}{stack}{\optional{context}}
383 Return a list of frame records for the caller's stack. The first
384 entry in the returned list represents the caller; the last entry
385 represents the outermost call on the stack.
386\end{funcdesc}
387
388\begin{funcdesc}{trace}{\optional{context}}
389 Return a list of frame records for the stack between the current
390 frame and the frame in which an exception currently being handled
391 was raised in. The first entry in the list represents the caller;
392 the last entry represents where the exception was raised.
393\end{funcdesc}