blob: 6568e94cc3fa00c3f8d2333ae3da2d9cf1cf6f27 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`inspect` --- Inspect live objects
2=======================================
3
4.. module:: inspect
5 :synopsis: Extract information and source code from live objects.
6.. moduleauthor:: Ka-Ping Yee <ping@lfw.org>
7.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
8
Raymond Hettinger469271d2011-01-27 20:38:46 +00009**Source code:** :source:`Lib/inspect.py`
10
11--------------
Georg Brandl116aa622007-08-15 14:28:22 +000012
Georg Brandl116aa622007-08-15 14:28:22 +000013The :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
Christian Heimes78644762008-03-04 23:39:23 +000031class or module. The sixteen functions whose names begin with "is" are mainly
Georg Brandl116aa622007-08-15 14:28:22 +000032provided 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
Georg Brandl55ac8f02007-09-01 13:51:09 +000036+-----------+-----------------+---------------------------+
37| Type | Attribute | Description |
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+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000054| | __func__ | function object |
Georg Brandl55ac8f02007-09-01 13:51:09 +000055| | | containing implementation |
56| | | of method |
57+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000058| | __self__ | instance to which this |
Georg Brandl55ac8f02007-09-01 13:51:09 +000059| | | method is bound, or |
60| | | ``None`` |
61+-----------+-----------------+---------------------------+
62| function | __doc__ | documentation string |
63+-----------+-----------------+---------------------------+
64| | __name__ | name with which this |
65| | | function was defined |
66+-----------+-----------------+---------------------------+
67| | __code__ | code object containing |
68| | | compiled function |
Georg Brandl9afde1c2007-11-01 20:32:30 +000069| | | :term:`bytecode` |
Georg Brandl55ac8f02007-09-01 13:51:09 +000070+-----------+-----------------+---------------------------+
71| | __defaults__ | tuple of any default |
72| | | values for arguments |
73+-----------+-----------------+---------------------------+
74| | __globals__ | global namespace in which |
75| | | this function was defined |
76+-----------+-----------------+---------------------------+
77| traceback | tb_frame | frame object at this |
78| | | level |
79+-----------+-----------------+---------------------------+
80| | tb_lasti | index of last attempted |
81| | | instruction in bytecode |
82+-----------+-----------------+---------------------------+
83| | tb_lineno | current line number in |
84| | | Python source code |
85+-----------+-----------------+---------------------------+
86| | tb_next | next inner traceback |
87| | | object (called by this |
88| | | level) |
89+-----------+-----------------+---------------------------+
90| frame | f_back | next outer frame object |
91| | | (this frame's caller) |
92+-----------+-----------------+---------------------------+
Georg Brandlc4a55fc2010-02-06 18:46:57 +000093| | f_builtins | builtins namespace seen |
Georg Brandl55ac8f02007-09-01 13:51:09 +000094| | | by this frame |
95+-----------+-----------------+---------------------------+
96| | f_code | code object being |
97| | | executed in this frame |
98+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +000099| | f_globals | global namespace seen by |
100| | | this frame |
101+-----------+-----------------+---------------------------+
102| | f_lasti | index of last attempted |
103| | | instruction in bytecode |
104+-----------+-----------------+---------------------------+
105| | f_lineno | current line number in |
106| | | Python source code |
107+-----------+-----------------+---------------------------+
108| | f_locals | local namespace seen by |
109| | | this frame |
110+-----------+-----------------+---------------------------+
111| | f_restricted | 0 or 1 if frame is in |
112| | | restricted execution mode |
113+-----------+-----------------+---------------------------+
114| | f_trace | tracing function for this |
115| | | frame, or ``None`` |
116+-----------+-----------------+---------------------------+
117| code | co_argcount | number of arguments (not |
118| | | including \* or \*\* |
119| | | args) |
120+-----------+-----------------+---------------------------+
121| | co_code | string of raw compiled |
122| | | bytecode |
123+-----------+-----------------+---------------------------+
124| | co_consts | tuple of constants used |
125| | | in the bytecode |
126+-----------+-----------------+---------------------------+
127| | co_filename | name of file in which |
128| | | this code object was |
129| | | created |
130+-----------+-----------------+---------------------------+
131| | co_firstlineno | number of first line in |
132| | | Python source code |
133+-----------+-----------------+---------------------------+
134| | co_flags | bitmap: 1=optimized ``|`` |
135| | | 2=newlocals ``|`` 4=\*arg |
136| | | ``|`` 8=\*\*arg |
137+-----------+-----------------+---------------------------+
138| | co_lnotab | encoded mapping of line |
139| | | numbers to bytecode |
140| | | indices |
141+-----------+-----------------+---------------------------+
142| | co_name | name with which this code |
143| | | object was defined |
144+-----------+-----------------+---------------------------+
145| | co_names | tuple of names of local |
146| | | variables |
147+-----------+-----------------+---------------------------+
148| | co_nlocals | number of local variables |
149+-----------+-----------------+---------------------------+
150| | co_stacksize | virtual machine stack |
151| | | space required |
152+-----------+-----------------+---------------------------+
153| | co_varnames | tuple of names of |
154| | | arguments and local |
155| | | variables |
156+-----------+-----------------+---------------------------+
157| builtin | __doc__ | documentation string |
158+-----------+-----------------+---------------------------+
159| | __name__ | original name of this |
160| | | function or method |
161+-----------+-----------------+---------------------------+
162| | __self__ | instance to which a |
163| | | method is bound, or |
164| | | ``None`` |
165+-----------+-----------------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000166
167
168.. function:: getmembers(object[, predicate])
169
170 Return all the members of an object in a list of (name, value) pairs sorted by
171 name. If the optional *predicate* argument is supplied, only members for which
172 the predicate returns a true value are included.
173
Christian Heimes7f044312008-01-06 17:05:40 +0000174 .. note::
175
176 :func:`getmembers` does not return metaclass attributes when the argument
177 is a class (this behavior is inherited from the :func:`dir` function).
178
Georg Brandl116aa622007-08-15 14:28:22 +0000179
180.. function:: getmoduleinfo(path)
181
Georg Brandlb30f3302011-01-06 09:23:56 +0000182 Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode, module_type)``
183 of values that describe how Python will interpret the file identified by
184 *path* if it is a module, or ``None`` if it would not be identified as a
185 module. In that tuple, *name* is the name of the module without the name of
186 any enclosing package, *suffix* is the trailing part of the file name (which
187 may not be a dot-delimited extension), *mode* is the :func:`open` mode that
188 would be used (``'r'`` or ``'rb'``), and *module_type* is an integer giving
189 the type of the module. *module_type* will have a value which can be
190 compared to the constants defined in the :mod:`imp` module; see the
191 documentation for that module for more information on module types.
Georg Brandl116aa622007-08-15 14:28:22 +0000192
Brett Cannoncb66eb02012-05-11 12:58:42 -0400193 .. deprecated:: 3.3
194 You may check the file path's suffix against the supported suffixes
195 listed in :mod:`importlib.machinery` to infer the same information.
196
Georg Brandl116aa622007-08-15 14:28:22 +0000197
198.. function:: getmodulename(path)
199
200 Return the name of the module named by the file *path*, without including the
201 names of enclosing packages. This uses the same algorithm as the interpreter
202 uses when searching for modules. If the name cannot be matched according to the
203 interpreter's rules, ``None`` is returned.
204
205
206.. function:: ismodule(object)
207
208 Return true if the object is a module.
209
210
211.. function:: isclass(object)
212
Georg Brandl39cadc32010-10-15 16:53:24 +0000213 Return true if the object is a class, whether built-in or created in Python
214 code.
Georg Brandl116aa622007-08-15 14:28:22 +0000215
216
217.. function:: ismethod(object)
218
Georg Brandl39cadc32010-10-15 16:53:24 +0000219 Return true if the object is a bound method written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000220
221
222.. function:: isfunction(object)
223
Georg Brandl39cadc32010-10-15 16:53:24 +0000224 Return true if the object is a Python function, which includes functions
225 created by a :term:`lambda` expression.
Georg Brandl116aa622007-08-15 14:28:22 +0000226
227
Christian Heimes7131fd92008-02-19 14:21:46 +0000228.. function:: isgeneratorfunction(object)
229
230 Return true if the object is a Python generator function.
231
232
233.. function:: isgenerator(object)
234
235 Return true if the object is a generator.
236
237
Georg Brandl116aa622007-08-15 14:28:22 +0000238.. function:: istraceback(object)
239
240 Return true if the object is a traceback.
241
242
243.. function:: isframe(object)
244
245 Return true if the object is a frame.
246
247
248.. function:: iscode(object)
249
250 Return true if the object is a code.
251
252
253.. function:: isbuiltin(object)
254
Georg Brandl39cadc32010-10-15 16:53:24 +0000255 Return true if the object is a built-in function or a bound built-in method.
Georg Brandl116aa622007-08-15 14:28:22 +0000256
257
258.. function:: isroutine(object)
259
260 Return true if the object is a user-defined or built-in function or method.
261
Georg Brandl39cadc32010-10-15 16:53:24 +0000262
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000263.. function:: isabstract(object)
264
265 Return true if the object is an abstract base class.
266
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268.. function:: ismethoddescriptor(object)
269
Georg Brandl39cadc32010-10-15 16:53:24 +0000270 Return true if the object is a method descriptor, but not if
271 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
272 are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000273
Georg Brandle6bcc912008-05-12 18:05:20 +0000274 This, for example, is true of ``int.__add__``. An object passing this test
275 has a :attr:`__get__` attribute but not a :attr:`__set__` attribute, but
276 beyond that the set of attributes varies. :attr:`__name__` is usually
277 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Georg Brandl9afde1c2007-11-01 20:32:30 +0000279 Methods implemented via descriptors that also pass one of the other tests
280 return false from the :func:`ismethoddescriptor` test, simply because the
281 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000282 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000283
284
285.. function:: isdatadescriptor(object)
286
287 Return true if the object is a data descriptor.
288
Georg Brandl9afde1c2007-11-01 20:32:30 +0000289 Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute.
290 Examples are properties (defined in Python), getsets, and members. The
291 latter two are defined in C and there are more specific tests available for
292 those types, which is robust across Python implementations. Typically, data
293 descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes
294 (properties, getsets, and members have both of these attributes), but this is
295 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000296
Georg Brandl116aa622007-08-15 14:28:22 +0000297
298.. function:: isgetsetdescriptor(object)
299
300 Return true if the object is a getset descriptor.
301
Georg Brandl495f7b52009-10-27 15:28:25 +0000302 .. impl-detail::
303
304 getsets are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000305 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000306 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000307
Georg Brandl116aa622007-08-15 14:28:22 +0000308
309.. function:: ismemberdescriptor(object)
310
311 Return true if the object is a member descriptor.
312
Georg Brandl495f7b52009-10-27 15:28:25 +0000313 .. impl-detail::
314
315 Member descriptors are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000316 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000317 types, 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
Georg Brandl116aa622007-08-15 14:28:22 +0000325.. function:: getdoc(object)
326
Georg Brandl0c77a822008-06-10 16:37:50 +0000327 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Georg Brandl116aa622007-08-15 14:28:22 +0000328
329
330.. function:: getcomments(object)
331
332 Return in a single string any lines of comments immediately preceding the
333 object's source code (for a class, function, or method), or at the top of the
334 Python source file (if the object is a module).
335
336
337.. function:: getfile(object)
338
339 Return the name of the (text or binary) file in which an object was defined.
340 This will fail with a :exc:`TypeError` if the object is a built-in module,
341 class, or function.
342
343
344.. function:: getmodule(object)
345
346 Try to guess which module an object was defined in.
347
348
349.. function:: getsourcefile(object)
350
351 Return the name of the Python source file in which an object was defined. This
352 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
353 function.
354
355
356.. function:: getsourcelines(object)
357
358 Return a list of source lines and starting line number for an object. The
359 argument may be a module, class, method, function, traceback, frame, or code
360 object. The source code is returned as a list of the lines corresponding to the
361 object and the line number indicates where in the original source file the first
Antoine Pitrou62ab10a2011-10-12 20:10:51 +0200362 line of code was found. An :exc:`OSError` is raised if the source code cannot
Georg Brandl116aa622007-08-15 14:28:22 +0000363 be retrieved.
364
Antoine Pitrou62ab10a2011-10-12 20:10:51 +0200365 .. versionchanged:: 3.3
366 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
367 former.
368
Georg Brandl116aa622007-08-15 14:28:22 +0000369
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
Antoine Pitrou62ab10a2011-10-12 20:10:51 +0200374 returned as a single string. An :exc:`OSError` is raised if the source code
Georg Brandl116aa622007-08-15 14:28:22 +0000375 cannot be retrieved.
376
Antoine Pitrou62ab10a2011-10-12 20:10:51 +0200377 .. versionchanged:: 3.3
378 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
379 former.
380
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Georg Brandl0c77a822008-06-10 16:37:50 +0000382.. function:: cleandoc(doc)
383
384 Clean up indentation from docstrings that are indented to line up with blocks
385 of code. Any whitespace that can be uniformly removed from the second line
386 onwards is removed. Also, all tabs are expanded to spaces.
387
Georg Brandl0c77a822008-06-10 16:37:50 +0000388
Georg Brandl116aa622007-08-15 14:28:22 +0000389.. _inspect-classes-functions:
390
391Classes and functions
392---------------------
393
Georg Brandl3dd33882009-06-01 17:35:27 +0000394.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396 Arrange the given list of classes into a hierarchy of nested lists. Where a
397 nested list appears, it contains classes derived from the class whose entry
398 immediately precedes the list. Each entry is a 2-tuple containing a class and a
399 tuple of its base classes. If the *unique* argument is true, exactly one entry
400 appears in the returned structure for each class in the given list. Otherwise,
401 classes using multiple inheritance and their descendants will appear multiple
402 times.
403
404
405.. function:: getargspec(func)
406
Georg Brandl82402752010-01-09 09:48:46 +0000407 Get the names and default values of a Python function's arguments. A
Georg Brandlb30f3302011-01-06 09:23:56 +0000408 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
409 returned. *args* is a list of the argument names. *varargs* and *keywords*
410 are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a
411 tuple of default argument values or None if there are no default arguments;
412 if this tuple has *n* elements, they correspond to the last *n* elements
413 listed in *args*.
Georg Brandl138bcb52007-09-12 19:04:21 +0000414
415 .. deprecated:: 3.0
416 Use :func:`getfullargspec` instead, which provides information about
Benjamin Peterson3e8e9cc2008-11-12 21:26:46 +0000417 keyword-only arguments and annotations.
Georg Brandl138bcb52007-09-12 19:04:21 +0000418
419
420.. function:: getfullargspec(func)
421
Georg Brandl82402752010-01-09 09:48:46 +0000422 Get the names and default values of a Python function's arguments. A
423 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000424
Georg Brandl3dd33882009-06-01 17:35:27 +0000425 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
426 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000427
428 *args* is a list of the argument names. *varargs* and *varkw* are the names
429 of the ``*`` and ``**`` arguments or ``None``. *defaults* is an n-tuple of
430 the default values of the last n arguments. *kwonlyargs* is a list of
431 keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
432 from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
433 names to annotations.
434
435 The first four items in the tuple correspond to :func:`getargspec`.
Georg Brandl116aa622007-08-15 14:28:22 +0000436
437
438.. function:: getargvalues(frame)
439
Georg Brandl3dd33882009-06-01 17:35:27 +0000440 Get information about arguments passed into a particular frame. A
441 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000442 returned. *args* is a list of the argument names. *varargs* and *keywords*
443 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000444 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000445
446
Michael Foord3af125a2012-04-21 18:22:28 +0100447.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations])
Georg Brandl116aa622007-08-15 14:28:22 +0000448
Michael Foord3af125a2012-04-21 18:22:28 +0100449 Format a pretty argument spec from the values returned by
450 :func:`getargspec` or :func:`getfullargspec`.
451
452 The first seven arguments are (``args``, ``varargs``, ``varkw``,
453 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``). The
454 other five arguments are the corresponding optional formatting functions
455 that are called to turn names and values into strings. The last argument
456 is an optional function to format the sequence of arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000457
458
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000459.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000460
461 Format a pretty argument spec from the four values returned by
462 :func:`getargvalues`. The format\* arguments are the corresponding optional
463 formatting functions that are called to turn names and values into strings.
464
465
466.. function:: getmro(cls)
467
468 Return a tuple of class cls's base classes, including cls, in method resolution
469 order. No class appears more than once in this tuple. Note that the method
470 resolution order depends on cls's type. Unless a very peculiar user-defined
471 metatype is in use, cls will be the first element of the tuple.
472
473
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000474.. function:: getcallargs(func[, *args][, **kwds])
475
476 Bind the *args* and *kwds* to the argument names of the Python function or
477 method *func*, as if it was called with them. For bound methods, bind also the
478 first argument (typically named ``self``) to the associated instance. A dict
479 is returned, mapping the argument names (including the names of the ``*`` and
480 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
481 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
482 an exception because of incompatible signature, an exception of the same type
483 and the same or similar message is raised. For example::
484
485 >>> from inspect import getcallargs
486 >>> def f(a, b=1, *pos, **named):
487 ... pass
488 >>> getcallargs(f, 1, 2, 3)
489 {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
490 >>> getcallargs(f, a=2, x=4)
491 {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
492 >>> getcallargs(f)
493 Traceback (most recent call last):
494 ...
495 TypeError: f() takes at least 1 argument (0 given)
496
497 .. versionadded:: 3.2
498
499
Nick Coghlan2f92e542012-06-23 19:39:55 +1000500.. function:: getclosurevars(func)
501
502 Get the mapping of external name references in a Python function or
503 method *func* to their current values. A
504 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
505 is returned. *nonlocals* maps referenced names to lexical closure
506 variables, *globals* to the function's module globals and *builtins* to
507 the builtins visible from the function body. *unbound* is the set of names
508 referenced in the function that could not be resolved at all given the
509 current module globals and builtins.
510
511 :exc:`TypeError` is raised if *func* is not a Python function or method.
512
513 .. versionadded:: 3.3
514
515
Georg Brandl116aa622007-08-15 14:28:22 +0000516.. _inspect-stack:
517
518The interpreter stack
519---------------------
520
521When the following functions return "frame records," each record is a tuple of
522six items: the frame object, the filename, the line number of the current line,
523the function name, a list of lines of context from the source code, and the
524index of the current line within that list.
525
Georg Brandle720c0a2009-04-27 16:20:50 +0000526.. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000527
528 Keeping references to frame objects, as found in the first element of the frame
529 records these functions return, can cause your program to create reference
530 cycles. Once a reference cycle has been created, the lifespan of all objects
531 which can be accessed from the objects which form the cycle can become much
532 longer even if Python's optional cycle detector is enabled. If such cycles must
533 be created, it is important to ensure they are explicitly broken to avoid the
534 delayed destruction of objects and increased memory consumption which occurs.
535
536 Though the cycle detector will catch these, destruction of the frames (and local
537 variables) can be made deterministic by removing the cycle in a
538 :keyword:`finally` clause. This is also important if the cycle detector was
539 disabled when Python was compiled or using :func:`gc.disable`. For example::
540
541 def handle_stackframe_without_leak():
542 frame = inspect.currentframe()
543 try:
544 # do something with the frame
545 finally:
546 del frame
547
548The optional *context* argument supported by most of these functions specifies
549the number of lines of context to return, which are centered around the current
550line.
551
552
Georg Brandl3dd33882009-06-01 17:35:27 +0000553.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000554
Georg Brandl48310cd2009-01-03 21:18:54 +0000555 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +0000556 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000557
558
Georg Brandl3dd33882009-06-01 17:35:27 +0000559.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000560
561 Get a list of frame records for a frame and all outer frames. These frames
562 represent the calls that lead to the creation of *frame*. The first entry in the
563 returned list represents *frame*; the last entry represents the outermost call
564 on *frame*'s stack.
565
566
Georg Brandl3dd33882009-06-01 17:35:27 +0000567.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000568
569 Get a list of frame records for a traceback's frame and all inner frames. These
570 frames represent calls made as a consequence of *frame*. The first entry in the
571 list represents *traceback*; the last entry represents where the exception was
572 raised.
573
574
575.. function:: currentframe()
576
577 Return the frame object for the caller's stack frame.
578
Georg Brandl495f7b52009-10-27 15:28:25 +0000579 .. impl-detail::
580
581 This function relies on Python stack frame support in the interpreter,
582 which isn't guaranteed to exist in all implementations of Python. If
583 running in an implementation without Python stack frame support this
584 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000585
Georg Brandl116aa622007-08-15 14:28:22 +0000586
Georg Brandl3dd33882009-06-01 17:35:27 +0000587.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000588
589 Return a list of frame records for the caller's stack. The first entry in the
590 returned list represents the caller; the last entry represents the outermost
591 call on the stack.
592
593
Georg Brandl3dd33882009-06-01 17:35:27 +0000594.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000595
596 Return a list of frame records for the stack between the current frame and the
597 frame in which an exception currently being handled was raised in. The first
598 entry in the list represents the caller; the last entry represents where the
599 exception was raised.
600
Michael Foord95fc51d2010-11-20 15:07:30 +0000601
602Fetching attributes statically
603------------------------------
604
605Both :func:`getattr` and :func:`hasattr` can trigger code execution when
606fetching or checking for the existence of attributes. Descriptors, like
607properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
608may be called.
609
610For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +0200611can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +0000612but avoids executing code when it fetches attributes.
613
614.. function:: getattr_static(obj, attr, default=None)
615
616 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +0200617 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +0000618
619 Note: this function may not be able to retrieve all attributes
620 that getattr can fetch (like dynamically created attributes)
621 and may find attributes that getattr can't (like descriptors
622 that raise AttributeError). It can also return descriptors objects
623 instead of instance members.
624
Éric Araujo941afed2011-09-01 02:47:34 +0200625 If the instance :attr:`__dict__` is shadowed by another member (for example a
Michael Foorddcebe0f2011-03-15 19:20:44 -0400626 property) then this function will be unable to find instance members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +0000627
Michael Foorddcebe0f2011-03-15 19:20:44 -0400628 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +0000629
Éric Araujo941afed2011-09-01 02:47:34 +0200630:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +0000631getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +0000632is returned instead of the underlying attribute.
633
634You can handle these with code like the following. Note that
635for arbitrary getset descriptors invoking these may trigger
636code execution::
637
638 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +0000639 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +0000640 __slots__ = ['foo']
641
642 slot_descriptor = type(_foo.foo)
643 getset_descriptor = type(type(open(__file__)).name)
644 wrapper_descriptor = type(str.__dict__['__add__'])
645 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
646
647 result = getattr_static(some_object, 'foo')
648 if type(result) in descriptor_types:
649 try:
650 result = result.__get__()
651 except AttributeError:
652 # descriptors can raise AttributeError to
653 # indicate there is no underlying value
654 # in which case the descriptor itself will
655 # have to do
656 pass
Nick Coghlane0f04652010-11-21 03:44:04 +0000657
Nick Coghlan2dad5ca2010-11-21 03:55:53 +0000658
Nick Coghlane0f04652010-11-21 03:44:04 +0000659Current State of a Generator
660----------------------------
661
662When implementing coroutine schedulers and for other advanced uses of
663generators, it is useful to determine whether a generator is currently
664executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +0000665terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +0000666generator to be determined easily.
667
668.. function:: getgeneratorstate(generator)
669
Raymond Hettinger48f3bd32010-12-16 00:30:53 +0000670 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +0000671
Raymond Hettinger48f3bd32010-12-16 00:30:53 +0000672 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +0000673 * GEN_CREATED: Waiting to start execution.
674 * GEN_RUNNING: Currently being executed by the interpreter.
675 * GEN_SUSPENDED: Currently suspended at a yield expression.
676 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +0000677
Nick Coghlan2dad5ca2010-11-21 03:55:53 +0000678 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +1000679
680The current internal state of the generator can also be queried. This is
681mostly useful for testing purposes, to ensure that internal state is being
682updated as expected:
683
684.. function:: getgeneratorlocals(generator)
685
686 Get the mapping of live local variables in *generator* to their current
687 values. A dictionary is returned that maps from variable names to values.
688 This is the equivalent of calling :func:`locals` in the body of the
689 generator, and all the same caveats apply.
690
691 If *generator* is a :term:`generator` with no currently associated frame,
692 then an empty dictionary is returned. :exc:`TypeError` is raised if
693 *generator* is not a Python generator object.
694
695 .. impl-detail::
696
697 This function relies on the generator exposing a Python stack frame
698 for introspection, which isn't guaranteed to be the case in all
699 implementations of Python. In such cases, this function will always
700 return an empty dictionary.
701
702 .. versionadded:: 3.3