blob: c9a63fc93e21344d7fbcee9da866c5d81999f38f [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}{}
Neal Norwitz221085d2007-02-25 20:55:47 +000048 \lineiv{}{__code__}{code object containing compiled function bytecode}{}
49 \lineiv{}{__defaults__}{tuple of any default values for arguments}{}
50 \lineiv{}{__globals__}{global namespace in which this function was defined}{}
Fred Drake6dbd3822001-02-28 23:01:38 +000051 \hline
Fred Drakef9d58032001-12-07 23:13:53 +000052 \lineiv{traceback}{tb_frame}{frame object at this level}{}
53 \lineiv{}{tb_lasti}{index of last attempted instruction in bytecode}{}
54 \lineiv{}{tb_lineno}{current line number in Python source code}{}
55 \lineiv{}{tb_next}{next inner traceback object (called by this level)}{}
Fred Drake6dbd3822001-02-28 23:01:38 +000056 \hline
Fred Drakef9d58032001-12-07 23:13:53 +000057 \lineiv{frame}{f_back}{next outer frame object (this frame's caller)}{}
58 \lineiv{}{f_builtins}{built-in namespace seen by this frame}{}
59 \lineiv{}{f_code}{code object being executed in this frame}{}
60 \lineiv{}{f_exc_traceback}{traceback if raised in this frame, or \code{None}}{}
61 \lineiv{}{f_exc_type}{exception type if raised in this frame, or \code{None}}{}
62 \lineiv{}{f_exc_value}{exception value if raised in this frame, or \code{None}}{}
63 \lineiv{}{f_globals}{global namespace seen by this frame}{}
64 \lineiv{}{f_lasti}{index of last attempted instruction in bytecode}{}
65 \lineiv{}{f_lineno}{current line number in Python source code}{}
66 \lineiv{}{f_locals}{local namespace seen by this frame}{}
67 \lineiv{}{f_restricted}{0 or 1 if frame is in restricted execution mode}{}
68 \lineiv{}{f_trace}{tracing function for this frame, or \code{None}}{}
Fred Drake6dbd3822001-02-28 23:01:38 +000069 \hline
Fred Drakef9d58032001-12-07 23:13:53 +000070 \lineiv{code}{co_argcount}{number of arguments (not including * or ** args)}{}
71 \lineiv{}{co_code}{string of raw compiled bytecode}{}
72 \lineiv{}{co_consts}{tuple of constants used in the bytecode}{}
73 \lineiv{}{co_filename}{name of file in which this code object was created}{}
74 \lineiv{}{co_firstlineno}{number of first line in Python source code}{}
75 \lineiv{}{co_flags}{bitmap: 1=optimized \code{|} 2=newlocals \code{|} 4=*arg \code{|} 8=**arg}{}
76 \lineiv{}{co_lnotab}{encoded mapping of line numbers to bytecode indices}{}
77 \lineiv{}{co_name}{name with which this code object was defined}{}
78 \lineiv{}{co_names}{tuple of names of local variables}{}
79 \lineiv{}{co_nlocals}{number of local variables}{}
80 \lineiv{}{co_stacksize}{virtual machine stack space required}{}
81 \lineiv{}{co_varnames}{tuple of names of arguments and local variables}{}
Fred Drake6dbd3822001-02-28 23:01:38 +000082 \hline
Fred Drakef9d58032001-12-07 23:13:53 +000083 \lineiv{builtin}{__doc__}{documentation string}{}
84 \lineiv{}{__name__}{original name of this function or method}{}
85 \lineiv{}{__self__}{instance to which a method is bound, or \code{None}}{}
86\end{tableiv}
87
88\noindent
89Note:
90\begin{description}
91\item[(1)]
92\versionchanged[\member{im_class} used to refer to the class that
93 defined the method]{2.2}
94\end{description}
95
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +000096
97\begin{funcdesc}{getmembers}{object\optional{, predicate}}
98 Return all the members of an object in a list of (name, value) pairs
99 sorted by name. If the optional \var{predicate} argument is supplied,
100 only members for which the predicate returns a true value are included.
101\end{funcdesc}
102
Fred Drake90a72f82001-04-10 15:12:34 +0000103\begin{funcdesc}{getmoduleinfo}{path}
104 Return a tuple of values that describe how Python will interpret the
105 file identified by \var{path} if it is a module, or \code{None} if
106 it would not be identified as a module. The return tuple is
107 \code{(\var{name}, \var{suffix}, \var{mode}, \var{mtype})}, where
108 \var{name} is the name of the module without the name of any
109 enclosing package, \var{suffix} is the trailing part of the file
110 name (which may not be a dot-delimited extension), \var{mode} is the
111 \function{open()} mode that would be used (\code{'r'} or
112 \code{'rb'}), and \var{mtype} is an integer giving the type of the
113 module. \var{mtype} will have a value which can be compared to the
114 constants defined in the \refmodule{imp} module; see the
115 documentation for that module for more information on module types.
116\end{funcdesc}
117
118\begin{funcdesc}{getmodulename}{path}
119 Return the name of the module named by the file \var{path}, without
120 including the names of enclosing packages. This uses the same
Fred Drakebb066cf2004-05-12 03:07:27 +0000121 algorithm as the interpreter uses when searching for modules. If
Fred Drake90a72f82001-04-10 15:12:34 +0000122 the name cannot be matched according to the interpreter's rules,
123 \code{None} is returned.
124\end{funcdesc}
125
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000126\begin{funcdesc}{ismodule}{object}
127 Return true if the object is a module.
128\end{funcdesc}
129
130\begin{funcdesc}{isclass}{object}
131 Return true if the object is a class.
132\end{funcdesc}
133
134\begin{funcdesc}{ismethod}{object}
135 Return true if the object is a method.
136\end{funcdesc}
137
138\begin{funcdesc}{isfunction}{object}
139 Return true if the object is a Python function or unnamed (lambda) function.
140\end{funcdesc}
141
142\begin{funcdesc}{istraceback}{object}
143 Return true if the object is a traceback.
144\end{funcdesc}
145
146\begin{funcdesc}{isframe}{object}
147 Return true if the object is a frame.
148\end{funcdesc}
149
150\begin{funcdesc}{iscode}{object}
151 Return true if the object is a code.
152\end{funcdesc}
153
154\begin{funcdesc}{isbuiltin}{object}
155 Return true if the object is a built-in function.
156\end{funcdesc}
157
158\begin{funcdesc}{isroutine}{object}
159 Return true if the object is a user-defined or built-in function or method.
160\end{funcdesc}
161
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000162\begin{funcdesc}{ismethoddescriptor}{object}
163 Return true if the object is a method descriptor, but not if ismethod() or
164 isclass() or isfunction() are true.
165
166 This is new as of Python 2.2, and, for example, is true of int.__add__.
167 An object passing this test has a __get__ attribute but not a __set__
168 attribute, but beyond that the set of attributes varies. __name__ is
169 usually sensible, and __doc__ often is.
170
171 Methods implemented via descriptors that also pass one of the other
172 tests return false from the ismethoddescriptor() test, simply because
173 the other tests promise more -- you can, e.g., count on having the
174 im_func attribute (etc) when an object passes ismethod().
175\end{funcdesc}
176
177\begin{funcdesc}{isdatadescriptor}{object}
178 Return true if the object is a data descriptor.
179
180 Data descriptors have both a __get__ and a __set__ attribute. Examples are
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000181 properties (defined in Python), getsets, and members. The latter two are
182 defined in C and there are more specific tests available for those types,
183 which is robust across Python implementations. Typically, data descriptors
184 will also have __name__ and __doc__ attributes (properties, getsets, and
185 members have both of these attributes), but this is not guaranteed.
Neal Norwitzd3d57682003-05-29 02:10:31 +0000186\versionadded{2.3}
Martin v. Löwise59e2ba2003-05-03 09:09:02 +0000187\end{funcdesc}
188
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000189\begin{funcdesc}{isgetsetdescriptor}{object}
190 Return true if the object is a getset descriptor.
191
192 getsets are attributes defined in extension modules via \code{PyGetSetDef}
193 structures. For Python implementations without such types, this method will
194 always return \code{False}.
195\versionadded{2.5}
196\end{funcdesc}
197
198\begin{funcdesc}{ismemberdescriptor}{object}
199 Return true if the object is a member descriptor.
200
201 Member descriptors are attributes defined in extension modules via
202 \code{PyMemberDef} structures. For Python implementations without such
203 types, this method will always return \code{False}.
204\versionadded{2.5}
205\end{funcdesc}
206
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000207\subsection{Retrieving source code
208 \label{inspect-source}}
209
210\begin{funcdesc}{getdoc}{object}
211 Get the documentation string for an object.
212 All tabs are expanded to spaces. To clean up docstrings that are
213 indented to line up with blocks of code, any whitespace than can be
214 uniformly removed from the second line onwards is removed.
215\end{funcdesc}
216
217\begin{funcdesc}{getcomments}{object}
218 Return in a single string any lines of comments immediately preceding
219 the object's source code (for a class, function, or method), or at the
220 top of the Python source file (if the object is a module).
221\end{funcdesc}
222
223\begin{funcdesc}{getfile}{object}
Fred Drake6dbd3822001-02-28 23:01:38 +0000224 Return the name of the (text or binary) file in which an object was
225 defined. This will fail with a \exception{TypeError} if the object
226 is a built-in module, class, or function.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000227\end{funcdesc}
228
229\begin{funcdesc}{getmodule}{object}
230 Try to guess which module an object was defined in.
231\end{funcdesc}
232
233\begin{funcdesc}{getsourcefile}{object}
Fred Drake6dbd3822001-02-28 23:01:38 +0000234 Return the name of the Python source file in which an object was
235 defined. This will fail with a \exception{TypeError} if the object
236 is a built-in module, class, or function.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000237\end{funcdesc}
238
239\begin{funcdesc}{getsourcelines}{object}
240 Return a list of source lines and starting line number for an object.
241 The argument may be a module, class, method, function, traceback, frame,
242 or code object. The source code is returned as a list of the lines
243 corresponding to the object and the line number indicates where in the
Fred Drake6dbd3822001-02-28 23:01:38 +0000244 original source file the first line of code was found. An
245 \exception{IOError} is raised if the source code cannot be retrieved.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000246\end{funcdesc}
247
248\begin{funcdesc}{getsource}{object}
249 Return the text of the source code for an object.
250 The argument may be a module, class, method, function, traceback, frame,
251 or code object. The source code is returned as a single string. An
Fred Drake6dbd3822001-02-28 23:01:38 +0000252 \exception{IOError} is raised if the source code cannot be retrieved.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000253\end{funcdesc}
254
255\subsection{Classes and functions
256 \label{inspect-classes-functions}}
257
258\begin{funcdesc}{getclasstree}{classes\optional{, unique}}
259 Arrange the given list of classes into a hierarchy of nested lists.
260 Where a nested list appears, it contains classes derived from the class
261 whose entry immediately precedes the list. Each entry is a 2-tuple
262 containing a class and a tuple of its base classes. If the \var{unique}
263 argument is true, exactly one entry appears in the returned structure
264 for each class in the given list. Otherwise, classes using multiple
265 inheritance and their descendants will appear multiple times.
266\end{funcdesc}
267
268\begin{funcdesc}{getargspec}{func}
269 Get the names and default values of a function's arguments.
Fred Drake6dbd3822001-02-28 23:01:38 +0000270 A tuple of four things is returned: \code{(\var{args},
271 \var{varargs}, \var{varkw}, \var{defaults})}.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000272 \var{args} is a list of the argument names (it may contain nested lists).
Fred Drake6dbd3822001-02-28 23:01:38 +0000273 \var{varargs} and \var{varkw} are the names of the \code{*} and
274 \code{**} arguments or \code{None}.
Brett Cannon91cc5cd2004-07-10 21:13:06 +0000275 \var{defaults} is a tuple of default argument values or None if there are no
276 default arguments; if this tuple has \var{n} elements, they correspond to
277 the last \var{n} elements listed in \var{args}.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000278\end{funcdesc}
279
280\begin{funcdesc}{getargvalues}{frame}
281 Get information about arguments passed into a particular frame.
Fred Drake6dbd3822001-02-28 23:01:38 +0000282 A tuple of four things is returned: \code{(\var{args},
283 \var{varargs}, \var{varkw}, \var{locals})}.
284 \var{args} is a list of the argument names (it may contain nested
285 lists).
286 \var{varargs} and \var{varkw} are the names of the \code{*} and
287 \code{**} arguments or \code{None}.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000288 \var{locals} is the locals dictionary of the given frame.
289\end{funcdesc}
290
291\begin{funcdesc}{formatargspec}{args\optional{, varargs, varkw, defaults,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000292 formatarg, formatvarargs, formatvarkw, formatvalue, join}}
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000293
Fred Drake6dbd3822001-02-28 23:01:38 +0000294 Format a pretty argument spec from the four values returned by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000295 \function{getargspec()}. The format* arguments are the
Fred Drake6dbd3822001-02-28 23:01:38 +0000296 corresponding optional formatting functions that are called to turn
297 names and values into strings.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000298\end{funcdesc}
299
300\begin{funcdesc}{formatargvalues}{args\optional{, varargs, varkw, locals,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000301 formatarg, formatvarargs, formatvarkw, formatvalue, join}}
Fred Drake6dbd3822001-02-28 23:01:38 +0000302 Format a pretty argument spec from the four values returned by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000303 \function{getargvalues()}. The format* arguments are the
Fred Drake6dbd3822001-02-28 23:01:38 +0000304 corresponding optional formatting functions that are called to turn
305 names and values into strings.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000306\end{funcdesc}
307
Tim Peterse0b2d7a2001-09-22 06:10:55 +0000308\begin{funcdesc}{getmro}{cls}
309 Return a tuple of class cls's base classes, including cls, in
310 method resolution order. No class appears more than once in this tuple.
311 Note that the method resolution order depends on cls's type. Unless a
312 very peculiar user-defined metatype is in use, cls will be the first
313 element of the tuple.
314\end{funcdesc}
315
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000316\subsection{The interpreter stack
317 \label{inspect-stack}}
318
Fred Drake6dbd3822001-02-28 23:01:38 +0000319When the following functions return ``frame records,'' each record
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000320is a tuple of six items: the frame object, the filename,
321the line number of the current line, the function name, a list of
322lines of context from the source code, and the index of the current
323line within that list.
Ka-Ping Yee6397c7c2001-02-27 14:43:21 +0000324
Fred Drake6237ef12004-01-01 07:21:14 +0000325\begin{notice}[warning]
326Keeping references to frame objects, as found in
Fred Draked635e3c2001-08-10 17:37:33 +0000327the first element of the frame records these functions return, can
328cause your program to create reference cycles. Once a reference cycle
329has been created, the lifespan of all objects which can be accessed
330from the objects which form the cycle can become much longer even if
331Python's optional cycle detector is enabled. If such cycles must be
332created, it is important to ensure they are explicitly broken to avoid
333the delayed destruction of objects and increased memory consumption
Fred Drake6237ef12004-01-01 07:21:14 +0000334which occurs.
Fred Draked635e3c2001-08-10 17:37:33 +0000335
Fred Drake6237ef12004-01-01 07:21:14 +0000336Though the cycle detector will catch these, destruction of the frames
337(and local variables) can be made deterministic by removing the cycle
338in a \keyword{finally} clause. This is also important if the cycle
339detector was disabled when Python was compiled or using
340\function{\refmodule{gc}.disable()}. For example:
Fred Drake99d170062002-04-23 21:21:20 +0000341
342\begin{verbatim}
343def handle_stackframe_without_leak():
344 frame = inspect.currentframe()
345 try:
346 # do something with the frame
347 finally:
348 del frame
349\end{verbatim}
Fred Drake6237ef12004-01-01 07:21:14 +0000350\end{notice}
351
352The optional \var{context} argument supported by most of these
353functions specifies the number of lines of context to return, which
354are centered around the current line.
355
356\begin{funcdesc}{getframeinfo}{frame\optional{, context}}
357 Get information about a frame or traceback object. A 5-tuple
358 is returned, the last five elements of the frame's frame record.
359\end{funcdesc}
360
361\begin{funcdesc}{getouterframes}{frame\optional{, context}}
362 Get a list of frame records for a frame and all outer frames. These
363 frames represent the calls that lead to the creation of \var{frame}.
364 The first entry in the returned list represents \var{frame}; the
365 last entry represents the outermost call on \var{frame}'s stack.
366\end{funcdesc}
367
368\begin{funcdesc}{getinnerframes}{traceback\optional{, context}}
369 Get a list of frame records for a traceback's frame and all inner
370 frames. These frames represent calls made as a consequence of
371 \var{frame}. The first entry in the list represents
372 \var{traceback}; the last entry represents where the exception was
373 raised.
374\end{funcdesc}
375
376\begin{funcdesc}{currentframe}{}
377 Return the frame object for the caller's stack frame.
378\end{funcdesc}
379
380\begin{funcdesc}{stack}{\optional{context}}
381 Return a list of frame records for the caller's stack. The first
382 entry in the returned list represents the caller; the last entry
383 represents the outermost call on the stack.
384\end{funcdesc}
385
386\begin{funcdesc}{trace}{\optional{context}}
387 Return a list of frame records for the stack between the current
388 frame and the frame in which an exception currently being handled
389 was raised in. The first entry in the list represents the caller;
390 the last entry represents where the exception was raised.
391\end{funcdesc}