blob: edec9d58f0ba13d11163082b12bcf9ccfae0c4d8 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`inspect` --- Inspect live objects
3=======================================
4
5.. module:: inspect
6 :synopsis: Extract information and source code from live objects.
7.. moduleauthor:: Ka-Ping Yee <ping@lfw.org>
8.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
9
10
11.. versionadded:: 2.1
12
13The :mod:`inspect` module provides several useful functions to help get
14information about live objects such as modules, classes, methods, functions,
15tracebacks, frame objects, and code objects. For example, it can help you
16examine the contents of a class, retrieve the source code of a method, extract
17and format the argument list for a function, or get all the information you need
18to display a detailed traceback.
19
20There are four main kinds of services provided by this module: type checking,
21getting source code, inspecting classes and functions, and examining the
22interpreter stack.
23
24
25.. _inspect-types:
26
27Types and members
28-----------------
29
30The :func:`getmembers` function retrieves the members of an object such as a
31class or module. The eleven functions whose names begin with "is" are mainly
32provided as convenient choices for the second argument to :func:`getmembers`.
33They also help you determine when you can expect to find the following special
34attributes:
35
36+-----------+-----------------+---------------------------+-------+
37| Type | Attribute | Description | Notes |
38+===========+=================+===========================+=======+
39| module | __doc__ | documentation string | |
40+-----------+-----------------+---------------------------+-------+
41| | __file__ | filename (missing for | |
42| | | built-in modules) | |
43+-----------+-----------------+---------------------------+-------+
44| class | __doc__ | documentation string | |
45+-----------+-----------------+---------------------------+-------+
46| | __module__ | name of module in which | |
47| | | this class was defined | |
48+-----------+-----------------+---------------------------+-------+
49| method | __doc__ | documentation string | |
50+-----------+-----------------+---------------------------+-------+
51| | __name__ | name with which this | |
52| | | method was defined | |
53+-----------+-----------------+---------------------------+-------+
54| | im_class | class object that asked | \(1) |
55| | | for this method | |
56+-----------+-----------------+---------------------------+-------+
57| | im_func | function object | |
58| | | containing implementation | |
59| | | of method | |
60+-----------+-----------------+---------------------------+-------+
61| | im_self | instance to which this | |
62| | | method is bound, or | |
63| | | ``None`` | |
64+-----------+-----------------+---------------------------+-------+
65| function | __doc__ | documentation string | |
66+-----------+-----------------+---------------------------+-------+
67| | __name__ | name with which this | |
68| | | function was defined | |
69+-----------+-----------------+---------------------------+-------+
70| | __code__ | code object containing | |
71| | | compiled function | |
72| | | bytecode | |
73+-----------+-----------------+---------------------------+-------+
74| | __defaults__ | tuple of any default | |
75| | | values for arguments | |
76+-----------+-----------------+---------------------------+-------+
77| | __globals__ | global namespace in which | |
78| | | this function was defined | |
79+-----------+-----------------+---------------------------+-------+
80| traceback | tb_frame | frame object at this | |
81| | | level | |
82+-----------+-----------------+---------------------------+-------+
83| | tb_lasti | index of last attempted | |
84| | | instruction in bytecode | |
85+-----------+-----------------+---------------------------+-------+
86| | tb_lineno | current line number in | |
87| | | Python source code | |
88+-----------+-----------------+---------------------------+-------+
89| | tb_next | next inner traceback | |
90| | | object (called by this | |
91| | | level) | |
92+-----------+-----------------+---------------------------+-------+
93| frame | f_back | next outer frame object | |
94| | | (this frame's caller) | |
95+-----------+-----------------+---------------------------+-------+
96| | f_builtins | built-in namespace seen | |
97| | | by this frame | |
98+-----------+-----------------+---------------------------+-------+
99| | f_code | code object being | |
100| | | executed in this frame | |
101+-----------+-----------------+---------------------------+-------+
102| | f_exc_traceback | traceback if raised in | |
103| | | this frame, or ``None`` | |
104+-----------+-----------------+---------------------------+-------+
105| | f_exc_type | exception type if raised | |
106| | | in this frame, or | |
107| | | ``None`` | |
108+-----------+-----------------+---------------------------+-------+
109| | f_exc_value | exception value if raised | |
110| | | in this frame, or | |
111| | | ``None`` | |
112+-----------+-----------------+---------------------------+-------+
113| | f_globals | global namespace seen by | |
114| | | this frame | |
115+-----------+-----------------+---------------------------+-------+
116| | f_lasti | index of last attempted | |
117| | | instruction in bytecode | |
118+-----------+-----------------+---------------------------+-------+
119| | f_lineno | current line number in | |
120| | | Python source code | |
121+-----------+-----------------+---------------------------+-------+
122| | f_locals | local namespace seen by | |
123| | | this frame | |
124+-----------+-----------------+---------------------------+-------+
125| | f_restricted | 0 or 1 if frame is in | |
126| | | restricted execution mode | |
127+-----------+-----------------+---------------------------+-------+
128| | f_trace | tracing function for this | |
129| | | frame, or ``None`` | |
130+-----------+-----------------+---------------------------+-------+
131| code | co_argcount | number of arguments (not | |
132| | | including \* or \*\* | |
133| | | args) | |
134+-----------+-----------------+---------------------------+-------+
135| | co_code | string of raw compiled | |
136| | | bytecode | |
137+-----------+-----------------+---------------------------+-------+
138| | co_consts | tuple of constants used | |
139| | | in the bytecode | |
140+-----------+-----------------+---------------------------+-------+
141| | co_filename | name of file in which | |
142| | | this code object was | |
143| | | created | |
144+-----------+-----------------+---------------------------+-------+
145| | co_firstlineno | number of first line in | |
146| | | Python source code | |
147+-----------+-----------------+---------------------------+-------+
148| | co_flags | bitmap: 1=optimized ``|`` | |
149| | | 2=newlocals ``|`` 4=\*arg | |
150| | | ``|`` 8=\*\*arg | |
151+-----------+-----------------+---------------------------+-------+
152| | co_lnotab | encoded mapping of line | |
153| | | numbers to bytecode | |
154| | | indices | |
155+-----------+-----------------+---------------------------+-------+
156| | co_name | name with which this code | |
157| | | object was defined | |
158+-----------+-----------------+---------------------------+-------+
159| | co_names | tuple of names of local | |
160| | | variables | |
161+-----------+-----------------+---------------------------+-------+
162| | co_nlocals | number of local variables | |
163+-----------+-----------------+---------------------------+-------+
164| | co_stacksize | virtual machine stack | |
165| | | space required | |
166+-----------+-----------------+---------------------------+-------+
167| | co_varnames | tuple of names of | |
168| | | arguments and local | |
169| | | variables | |
170+-----------+-----------------+---------------------------+-------+
171| builtin | __doc__ | documentation string | |
172+-----------+-----------------+---------------------------+-------+
173| | __name__ | original name of this | |
174| | | function or method | |
175+-----------+-----------------+---------------------------+-------+
176| | __self__ | instance to which a | |
177| | | method is bound, or | |
178| | | ``None`` | |
179+-----------+-----------------+---------------------------+-------+
180
181Note:
182
183(1)
184 .. versionchanged:: 2.2
185 :attr:`im_class` used to refer to the class that defined the method.
186
187
188.. function:: getmembers(object[, predicate])
189
190 Return all the members of an object in a list of (name, value) pairs sorted by
191 name. If the optional *predicate* argument is supplied, only members for which
192 the predicate returns a true value are included.
193
194
195.. function:: getmoduleinfo(path)
196
197 Return a tuple of values that describe how Python will interpret the file
198 identified by *path* if it is a module, or ``None`` if it would not be
199 identified as a module. The return tuple is ``(name, suffix, mode, mtype)``,
200 where *name* is the name of the module without the name of any enclosing
201 package, *suffix* is the trailing part of the file name (which may not be a
202 dot-delimited extension), *mode* is the :func:`open` mode that would be used
203 (``'r'`` or ``'rb'``), and *mtype* is an integer giving the type of the
204 module. *mtype* will have a value which can be compared to the constants
205 defined in the :mod:`imp` module; see the documentation for that module for
206 more information on module types.
207
208
209.. function:: getmodulename(path)
210
211 Return the name of the module named by the file *path*, without including the
212 names of enclosing packages. This uses the same algorithm as the interpreter
213 uses when searching for modules. If the name cannot be matched according to the
214 interpreter's rules, ``None`` is returned.
215
216
217.. function:: ismodule(object)
218
219 Return true if the object is a module.
220
221
222.. function:: isclass(object)
223
224 Return true if the object is a class.
225
226
227.. function:: ismethod(object)
228
229 Return true if the object is a method.
230
231
232.. function:: isfunction(object)
233
234 Return true if the object is a Python function or unnamed (lambda) function.
235
236
237.. function:: istraceback(object)
238
239 Return true if the object is a traceback.
240
241
242.. function:: isframe(object)
243
244 Return true if the object is a frame.
245
246
247.. function:: iscode(object)
248
249 Return true if the object is a code.
250
251
252.. function:: isbuiltin(object)
253
254 Return true if the object is a built-in function.
255
256
257.. function:: isroutine(object)
258
259 Return true if the object is a user-defined or built-in function or method.
260
261
262.. function:: ismethoddescriptor(object)
263
264 Return true if the object is a method descriptor, but not if ismethod() or
265 isclass() or isfunction() are true.
266
267 This is new as of Python 2.2, and, for example, is true of int.__add__. An
268 object passing this test has a __get__ attribute but not a __set__ attribute,
269 but beyond that the set of attributes varies. __name__ is usually sensible, and
270 __doc__ often is.
271
272 Methods implemented via descriptors that also pass one of the other tests return
273 false from the ismethoddescriptor() test, simply because the other tests promise
274 more -- you can, e.g., count on having the im_func attribute (etc) when an
275 object passes ismethod().
276
277
278.. function:: isdatadescriptor(object)
279
280 Return true if the object is a data descriptor.
281
282 Data descriptors have both a __get__ and a __set__ attribute. Examples are
283 properties (defined in Python), getsets, and members. The latter two are
284 defined in C and there are more specific tests available for those types, which
285 is robust across Python implementations. Typically, data descriptors will also
286 have __name__ and __doc__ attributes (properties, getsets, and members have both
287 of these attributes), but this is not guaranteed.
288
289 .. versionadded:: 2.3
290
291
292.. function:: isgetsetdescriptor(object)
293
294 Return true if the object is a getset descriptor.
295
296 getsets are attributes defined in extension modules via ``PyGetSetDef``
297 structures. For Python implementations without such types, this method will
298 always return ``False``.
299
300 .. versionadded:: 2.5
301
302
303.. function:: ismemberdescriptor(object)
304
305 Return true if the object is a member descriptor.
306
307 Member descriptors are attributes defined in extension modules via
308 ``PyMemberDef`` structures. For Python implementations without such types, this
309 method will always return ``False``.
310
311 .. versionadded:: 2.5
312
313
314.. _inspect-source:
315
316Retrieving source code
317----------------------
318
319
320.. function:: getdoc(object)
321
322 Get the documentation string for an object. All tabs are expanded to spaces. To
323 clean up docstrings that are indented to line up with blocks of code, any
324 whitespace than can be uniformly removed from the second line onwards is
325 removed.
326
327
328.. function:: getcomments(object)
329
330 Return in a single string any lines of comments immediately preceding the
331 object's source code (for a class, function, or method), or at the top of the
332 Python source file (if the object is a module).
333
334
335.. function:: getfile(object)
336
337 Return the name of the (text or binary) file in which an object was defined.
338 This will fail with a :exc:`TypeError` if the object is a built-in module,
339 class, or function.
340
341
342.. function:: getmodule(object)
343
344 Try to guess which module an object was defined in.
345
346
347.. function:: getsourcefile(object)
348
349 Return the name of the Python source file in which an object was defined. This
350 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
351 function.
352
353
354.. function:: getsourcelines(object)
355
356 Return a list of source lines and starting line number for an object. The
357 argument may be a module, class, method, function, traceback, frame, or code
358 object. The source code is returned as a list of the lines corresponding to the
359 object and the line number indicates where in the original source file the first
360 line of code was found. An :exc:`IOError` is raised if the source code cannot
361 be retrieved.
362
363
364.. function:: getsource(object)
365
366 Return the text of the source code for an object. The argument may be a module,
367 class, method, function, traceback, frame, or code object. The source code is
368 returned as a single string. An :exc:`IOError` is raised if the source code
369 cannot be retrieved.
370
371
372.. _inspect-classes-functions:
373
374Classes and functions
375---------------------
376
377
378.. function:: getclasstree(classes[, unique])
379
380 Arrange the given list of classes into a hierarchy of nested lists. Where a
381 nested list appears, it contains classes derived from the class whose entry
382 immediately precedes the list. Each entry is a 2-tuple containing a class and a
383 tuple of its base classes. If the *unique* argument is true, exactly one entry
384 appears in the returned structure for each class in the given list. Otherwise,
385 classes using multiple inheritance and their descendants will appear multiple
386 times.
387
388
389.. function:: getargspec(func)
390
391 Get the names and default values of a function's arguments. A tuple of four
392 things is returned: ``(args, varargs, varkw, defaults)``. *args* is a list of
393 the argument names (it may contain nested lists). *varargs* and *varkw* are the
394 names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a tuple of
395 default argument values or None if there are no default arguments; if this tuple
396 has *n* elements, they correspond to the last *n* elements listed in *args*.
397
398
399.. function:: getargvalues(frame)
400
401 Get information about arguments passed into a particular frame. A tuple of four
402 things is returned: ``(args, varargs, varkw, locals)``. *args* is a list of the
403 argument names (it may contain nested lists). *varargs* and *varkw* are the
404 names of the ``*`` and ``**`` arguments or ``None``. *locals* is the locals
405 dictionary of the given frame.
406
407
408.. function:: formatargspec(args[, varargs, varkw, defaults, formatarg, formatvarargs, formatvarkw, formatvalue, join])
409
410 Format a pretty argument spec from the four values returned by
411 :func:`getargspec`. The format\* arguments are the corresponding optional
412 formatting functions that are called to turn names and values into strings.
413
414
415.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue, join])
416
417 Format a pretty argument spec from the four values returned by
418 :func:`getargvalues`. The format\* arguments are the corresponding optional
419 formatting functions that are called to turn names and values into strings.
420
421
422.. function:: getmro(cls)
423
424 Return a tuple of class cls's base classes, including cls, in method resolution
425 order. No class appears more than once in this tuple. Note that the method
426 resolution order depends on cls's type. Unless a very peculiar user-defined
427 metatype is in use, cls will be the first element of the tuple.
428
429
430.. _inspect-stack:
431
432The interpreter stack
433---------------------
434
435When the following functions return "frame records," each record is a tuple of
436six items: the frame object, the filename, the line number of the current line,
437the function name, a list of lines of context from the source code, and the
438index of the current line within that list.
439
440.. warning::
441
442 Keeping references to frame objects, as found in the first element of the frame
443 records these functions return, can cause your program to create reference
444 cycles. Once a reference cycle has been created, the lifespan of all objects
445 which can be accessed from the objects which form the cycle can become much
446 longer even if Python's optional cycle detector is enabled. If such cycles must
447 be created, it is important to ensure they are explicitly broken to avoid the
448 delayed destruction of objects and increased memory consumption which occurs.
449
450 Though the cycle detector will catch these, destruction of the frames (and local
451 variables) can be made deterministic by removing the cycle in a
452 :keyword:`finally` clause. This is also important if the cycle detector was
453 disabled when Python was compiled or using :func:`gc.disable`. For example::
454
455 def handle_stackframe_without_leak():
456 frame = inspect.currentframe()
457 try:
458 # do something with the frame
459 finally:
460 del frame
461
462The optional *context* argument supported by most of these functions specifies
463the number of lines of context to return, which are centered around the current
464line.
465
466
467.. function:: getframeinfo(frame[, context])
468
469 Get information about a frame or traceback object. A 5-tuple is returned, the
470 last five elements of the frame's frame record.
471
472
473.. function:: getouterframes(frame[, context])
474
475 Get a list of frame records for a frame and all outer frames. These frames
476 represent the calls that lead to the creation of *frame*. The first entry in the
477 returned list represents *frame*; the last entry represents the outermost call
478 on *frame*'s stack.
479
480
481.. function:: getinnerframes(traceback[, context])
482
483 Get a list of frame records for a traceback's frame and all inner frames. These
484 frames represent calls made as a consequence of *frame*. The first entry in the
485 list represents *traceback*; the last entry represents where the exception was
486 raised.
487
488
489.. function:: currentframe()
490
491 Return the frame object for the caller's stack frame.
492
493
494.. function:: stack([context])
495
496 Return a list of frame records for the caller's stack. The first entry in the
497 returned list represents the caller; the last entry represents the outermost
498 call on the stack.
499
500
501.. function:: trace([context])
502
503 Return a list of frame records for the stack between the current frame and the
504 frame in which an exception currently being handled was raised in. The first
505 entry in the list represents the caller; the last entry represents where the
506 exception was raised.
507