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