1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
|
\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}
\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}
|