blob: c1b7bec4ff4b164453a276ec65cb22e5d018d6c6 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
9
10.. versionadded:: 2.1
11
Éric Araujo29a0b572011-08-19 02:14:03 +020012**Source code:** :source:`Lib/inspect.py`
13
14--------------
15
Georg Brandl8ec7f652007-08-15 14:28:01 +000016The :mod:`inspect` module provides several useful functions to help get
17information about live objects such as modules, classes, methods, functions,
18tracebacks, frame objects, and code objects. For example, it can help you
19examine the contents of a class, retrieve the source code of a method, extract
20and format the argument list for a function, or get all the information you need
21to display a detailed traceback.
22
23There are four main kinds of services provided by this module: type checking,
24getting source code, inspecting classes and functions, and examining the
25interpreter stack.
26
27
28.. _inspect-types:
29
30Types and members
31-----------------
32
33The :func:`getmembers` function retrieves the members of an object such as a
Georg Brandl3e9d66f2008-03-03 20:37:55 +000034class or module. The sixteen functions whose names begin with "is" are mainly
Georg Brandl8ec7f652007-08-15 14:28:01 +000035provided as convenient choices for the second argument to :func:`getmembers`.
36They also help you determine when you can expect to find the following special
37attributes:
38
39+-----------+-----------------+---------------------------+-------+
40| Type | Attribute | Description | Notes |
41+===========+=================+===========================+=======+
42| module | __doc__ | documentation string | |
43+-----------+-----------------+---------------------------+-------+
44| | __file__ | filename (missing for | |
45| | | built-in modules) | |
46+-----------+-----------------+---------------------------+-------+
47| class | __doc__ | documentation string | |
48+-----------+-----------------+---------------------------+-------+
49| | __module__ | name of module in which | |
50| | | this class was defined | |
51+-----------+-----------------+---------------------------+-------+
52| method | __doc__ | documentation string | |
53+-----------+-----------------+---------------------------+-------+
54| | __name__ | name with which this | |
55| | | method was defined | |
56+-----------+-----------------+---------------------------+-------+
57| | im_class | class object that asked | \(1) |
58| | | for this method | |
59+-----------+-----------------+---------------------------+-------+
Georg Brandl3fbe20c2008-03-21 19:20:21 +000060| | im_func or | function object | |
61| | __func__ | containing implementation | |
Georg Brandl8ec7f652007-08-15 14:28:01 +000062| | | of method | |
63+-----------+-----------------+---------------------------+-------+
Georg Brandl3fbe20c2008-03-21 19:20:21 +000064| | im_self or | instance to which this | |
65| | __self__ | method is bound, or | |
Georg Brandl8ec7f652007-08-15 14:28:01 +000066| | | ``None`` | |
67+-----------+-----------------+---------------------------+-------+
68| function | __doc__ | documentation string | |
69+-----------+-----------------+---------------------------+-------+
70| | __name__ | name with which this | |
71| | | function was defined | |
72+-----------+-----------------+---------------------------+-------+
73| | func_code | code object containing | |
74| | | compiled function | |
Georg Brandl63fa1682007-10-21 10:24:20 +000075| | | :term:`bytecode` | |
Georg Brandl8ec7f652007-08-15 14:28:01 +000076+-----------+-----------------+---------------------------+-------+
77| | func_defaults | tuple of any default | |
78| | | values for arguments | |
79+-----------+-----------------+---------------------------+-------+
80| | func_doc | (same as __doc__) | |
81+-----------+-----------------+---------------------------+-------+
82| | func_globals | global namespace in which | |
83| | | this function was defined | |
84+-----------+-----------------+---------------------------+-------+
85| | func_name | (same as __name__) | |
86+-----------+-----------------+---------------------------+-------+
Facundo Batista759bfc62008-02-18 03:43:43 +000087| generator | __iter__ | defined to support | |
88| | | iteration over container | |
89+-----------+-----------------+---------------------------+-------+
90| | close | raises new GeneratorExit | |
91| | | exception inside the | |
92| | | generator to terminate | |
93| | | the iteration | |
94+-----------+-----------------+---------------------------+-------+
95| | gi_code | code object | |
96+-----------+-----------------+---------------------------+-------+
97| | gi_frame | frame object or possibly | |
98| | | None once the generator | |
99| | | has been exhausted | |
100+-----------+-----------------+---------------------------+-------+
101| | gi_running | set to 1 when generator | |
102| | | is executing, 0 otherwise | |
103+-----------+-----------------+---------------------------+-------+
104| | next | return the next item from | |
105| | | the container | |
106+-----------+-----------------+---------------------------+-------+
107| | send | resumes the generator and | |
108| | | "sends" a value that | |
109| | | becomes the result of the | |
110| | | current yield-expression | |
111+-----------+-----------------+---------------------------+-------+
112| | throw | used to raise an | |
113| | | exception inside the | |
114| | | generator | |
115+-----------+-----------------+---------------------------+-------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000116| traceback | tb_frame | frame object at this | |
117| | | level | |
118+-----------+-----------------+---------------------------+-------+
119| | tb_lasti | index of last attempted | |
120| | | instruction in bytecode | |
121+-----------+-----------------+---------------------------+-------+
122| | tb_lineno | current line number in | |
123| | | Python source code | |
124+-----------+-----------------+---------------------------+-------+
125| | tb_next | next inner traceback | |
126| | | object (called by this | |
127| | | level) | |
128+-----------+-----------------+---------------------------+-------+
129| frame | f_back | next outer frame object | |
130| | | (this frame's caller) | |
131+-----------+-----------------+---------------------------+-------+
Georg Brandl6f82cd32010-02-06 18:44:44 +0000132| | f_builtins | builtins namespace seen | |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000133| | | by this frame | |
134+-----------+-----------------+---------------------------+-------+
135| | f_code | code object being | |
136| | | executed in this frame | |
137+-----------+-----------------+---------------------------+-------+
138| | f_exc_traceback | traceback if raised in | |
139| | | this frame, or ``None`` | |
140+-----------+-----------------+---------------------------+-------+
141| | f_exc_type | exception type if raised | |
142| | | in this frame, or | |
143| | | ``None`` | |
144+-----------+-----------------+---------------------------+-------+
145| | f_exc_value | exception value if raised | |
146| | | in this frame, or | |
147| | | ``None`` | |
148+-----------+-----------------+---------------------------+-------+
149| | f_globals | global namespace seen by | |
150| | | this frame | |
151+-----------+-----------------+---------------------------+-------+
152| | f_lasti | index of last attempted | |
153| | | instruction in bytecode | |
154+-----------+-----------------+---------------------------+-------+
155| | f_lineno | current line number in | |
156| | | Python source code | |
157+-----------+-----------------+---------------------------+-------+
158| | f_locals | local namespace seen by | |
159| | | this frame | |
160+-----------+-----------------+---------------------------+-------+
161| | f_restricted | 0 or 1 if frame is in | |
162| | | restricted execution mode | |
163+-----------+-----------------+---------------------------+-------+
164| | f_trace | tracing function for this | |
165| | | frame, or ``None`` | |
166+-----------+-----------------+---------------------------+-------+
167| code | co_argcount | number of arguments (not | |
168| | | including \* or \*\* | |
169| | | args) | |
170+-----------+-----------------+---------------------------+-------+
171| | co_code | string of raw compiled | |
172| | | bytecode | |
173+-----------+-----------------+---------------------------+-------+
174| | co_consts | tuple of constants used | |
175| | | in the bytecode | |
176+-----------+-----------------+---------------------------+-------+
177| | co_filename | name of file in which | |
178| | | this code object was | |
179| | | created | |
180+-----------+-----------------+---------------------------+-------+
181| | co_firstlineno | number of first line in | |
182| | | Python source code | |
183+-----------+-----------------+---------------------------+-------+
184| | co_flags | bitmap: 1=optimized ``|`` | |
185| | | 2=newlocals ``|`` 4=\*arg | |
186| | | ``|`` 8=\*\*arg | |
187+-----------+-----------------+---------------------------+-------+
188| | co_lnotab | encoded mapping of line | |
189| | | numbers to bytecode | |
190| | | indices | |
191+-----------+-----------------+---------------------------+-------+
192| | co_name | name with which this code | |
193| | | object was defined | |
194+-----------+-----------------+---------------------------+-------+
195| | co_names | tuple of names of local | |
196| | | variables | |
197+-----------+-----------------+---------------------------+-------+
198| | co_nlocals | number of local variables | |
199+-----------+-----------------+---------------------------+-------+
200| | co_stacksize | virtual machine stack | |
201| | | space required | |
202+-----------+-----------------+---------------------------+-------+
203| | co_varnames | tuple of names of | |
204| | | arguments and local | |
205| | | variables | |
206+-----------+-----------------+---------------------------+-------+
207| builtin | __doc__ | documentation string | |
208+-----------+-----------------+---------------------------+-------+
209| | __name__ | original name of this | |
210| | | function or method | |
211+-----------+-----------------+---------------------------+-------+
212| | __self__ | instance to which a | |
213| | | method is bound, or | |
214| | | ``None`` | |
215+-----------+-----------------+---------------------------+-------+
216
217Note:
218
219(1)
220 .. versionchanged:: 2.2
221 :attr:`im_class` used to refer to the class that defined the method.
222
223
224.. function:: getmembers(object[, predicate])
225
226 Return all the members of an object in a list of (name, value) pairs sorted by
227 name. If the optional *predicate* argument is supplied, only members for which
228 the predicate returns a true value are included.
229
Georg Brandl91a48082008-01-06 15:48:20 +0000230 .. note::
231
232 :func:`getmembers` does not return metaclass attributes when the argument
233 is a class (this behavior is inherited from the :func:`dir` function).
234
Georg Brandl8ec7f652007-08-15 14:28:01 +0000235
236.. function:: getmoduleinfo(path)
237
238 Return a tuple of values that describe how Python will interpret the file
239 identified by *path* if it is a module, or ``None`` if it would not be
Georg Brandlcbb2e492011-01-09 08:04:37 +0000240 identified as a module. The return tuple is ``(name, suffix, mode,
241 module_type)``, where *name* is the name of the module without the name of
242 any enclosing package, *suffix* is the trailing part of the file name (which
243 may not be a dot-delimited extension), *mode* is the :func:`open` mode that
244 would be used (``'r'`` or ``'rb'``), and *module_type* is an integer giving
245 the type of the module. *module_type* will have a value which can be
246 compared to the constants defined in the :mod:`imp` module; see the
247 documentation for that module for more information on module types.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000248
Georg Brandle3c3db52008-01-11 09:55:53 +0000249 .. versionchanged:: 2.6
250 Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode,
251 module_type)``.
252
Georg Brandl8ec7f652007-08-15 14:28:01 +0000253
254.. function:: getmodulename(path)
255
256 Return the name of the module named by the file *path*, without including the
257 names of enclosing packages. This uses the same algorithm as the interpreter
258 uses when searching for modules. If the name cannot be matched according to the
259 interpreter's rules, ``None`` is returned.
260
261
262.. function:: ismodule(object)
263
264 Return true if the object is a module.
265
266
267.. function:: isclass(object)
268
Georg Brandl78f11ed2010-11-26 07:34:20 +0000269 Return true if the object is a class, whether built-in or created in Python
270 code.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000271
272
273.. function:: ismethod(object)
274
Victor Stinner498834b2016-03-11 11:27:46 +0100275 Return true if the object is a bound or unbound method written in Python.
276
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277
278
279.. function:: isfunction(object)
280
Georg Brandl78f11ed2010-11-26 07:34:20 +0000281 Return true if the object is a Python function, which includes functions
282 created by a :term:`lambda` expression.
283
Georg Brandl8ec7f652007-08-15 14:28:01 +0000284
Facundo Batista759bfc62008-02-18 03:43:43 +0000285.. function:: isgeneratorfunction(object)
286
287 Return true if the object is a Python generator function.
288
Andrew M. Kuchling3fe18432008-03-04 01:49:37 +0000289 .. versionadded:: 2.6
290
Georg Brandl78f11ed2010-11-26 07:34:20 +0000291
Facundo Batista759bfc62008-02-18 03:43:43 +0000292.. function:: isgenerator(object)
293
294 Return true if the object is a generator.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000295
Andrew M. Kuchling3fe18432008-03-04 01:49:37 +0000296 .. versionadded:: 2.6
297
Georg Brandl78f11ed2010-11-26 07:34:20 +0000298
Georg Brandl8ec7f652007-08-15 14:28:01 +0000299.. function:: istraceback(object)
300
301 Return true if the object is a traceback.
302
303
304.. function:: isframe(object)
305
306 Return true if the object is a frame.
307
308
309.. function:: iscode(object)
310
311 Return true if the object is a code.
312
313
314.. function:: isbuiltin(object)
315
Georg Brandl78f11ed2010-11-26 07:34:20 +0000316 Return true if the object is a built-in function or a bound built-in method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000317
318
319.. function:: isroutine(object)
320
321 Return true if the object is a user-defined or built-in function or method.
322
Georg Brandl78f11ed2010-11-26 07:34:20 +0000323
Christian Heimes608c1d82008-03-03 18:28:04 +0000324.. function:: isabstract(object)
325
326 Return true if the object is an abstract base class.
327
328 .. versionadded:: 2.6
329
Georg Brandl8ec7f652007-08-15 14:28:01 +0000330
331.. function:: ismethoddescriptor(object)
332
Georg Brandl78f11ed2010-11-26 07:34:20 +0000333 Return true if the object is a method descriptor, but not if
334 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
335 are true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000336
Georg Brandl5c174bb2007-10-21 10:32:54 +0000337 This is new as of Python 2.2, and, for example, is true of
Martin Panterd51b0f22016-06-18 03:57:31 +0000338 ``int.__add__``. An object passing this test
339 has a :meth:`~object.__get__` method but not a :meth:`~object.__set__`
340 method, but beyond that the set of attributes varies. A
341 :attr:`~definition.__name__` attribute is usually
342 sensible, and :attr:`__doc__` often is.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000343
Georg Brandl5c174bb2007-10-21 10:32:54 +0000344 Methods implemented via descriptors that also pass one of the other tests
345 return false from the :func:`ismethoddescriptor` test, simply because the
346 other tests promise more -- you can, e.g., count on having the
347 :attr:`im_func` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000348
349
350.. function:: isdatadescriptor(object)
351
352 Return true if the object is a data descriptor.
353
Martin Panterd51b0f22016-06-18 03:57:31 +0000354 Data descriptors have both a :attr:`~object.__get__` and a :attr:`~object.__set__` method.
Georg Brandl5c174bb2007-10-21 10:32:54 +0000355 Examples are properties (defined in Python), getsets, and members. The
356 latter two are defined in C and there are more specific tests available for
357 those types, which is robust across Python implementations. Typically, data
Martin Panterd51b0f22016-06-18 03:57:31 +0000358 descriptors will also have :attr:`~definition.__name__` and :attr:`__doc__` attributes
Georg Brandl5c174bb2007-10-21 10:32:54 +0000359 (properties, getsets, and members have both of these attributes), but this is
360 not guaranteed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000361
362 .. versionadded:: 2.3
363
364
365.. function:: isgetsetdescriptor(object)
366
367 Return true if the object is a getset descriptor.
368
Georg Brandl6c14e582009-10-22 11:48:10 +0000369 .. impl-detail::
370
371 getsets are attributes defined in extension modules via
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100372 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl6c14e582009-10-22 11:48:10 +0000373 types, this method will always return ``False``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000374
375 .. versionadded:: 2.5
376
377
378.. function:: ismemberdescriptor(object)
379
380 Return true if the object is a member descriptor.
381
Georg Brandl6c14e582009-10-22 11:48:10 +0000382 .. impl-detail::
383
384 Member descriptors are attributes defined in extension modules via
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100385 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl6c14e582009-10-22 11:48:10 +0000386 types, this method will always return ``False``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000387
388 .. versionadded:: 2.5
389
390
391.. _inspect-source:
392
393Retrieving source code
394----------------------
395
Georg Brandl8ec7f652007-08-15 14:28:01 +0000396.. function:: getdoc(object)
397
Georg Brandl7be19aa2008-06-07 15:59:10 +0000398 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000399
400
401.. function:: getcomments(object)
402
403 Return in a single string any lines of comments immediately preceding the
404 object's source code (for a class, function, or method), or at the top of the
405 Python source file (if the object is a module).
406
407
408.. function:: getfile(object)
409
410 Return the name of the (text or binary) file in which an object was defined.
411 This will fail with a :exc:`TypeError` if the object is a built-in module,
412 class, or function.
413
414
415.. function:: getmodule(object)
416
417 Try to guess which module an object was defined in.
418
419
420.. function:: getsourcefile(object)
421
422 Return the name of the Python source file in which an object was defined. This
423 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
424 function.
425
426
427.. function:: getsourcelines(object)
428
429 Return a list of source lines and starting line number for an object. The
430 argument may be a module, class, method, function, traceback, frame, or code
431 object. The source code is returned as a list of the lines corresponding to the
432 object and the line number indicates where in the original source file the first
433 line of code was found. An :exc:`IOError` is raised if the source code cannot
434 be retrieved.
435
436
437.. function:: getsource(object)
438
439 Return the text of the source code for an object. The argument may be a module,
440 class, method, function, traceback, frame, or code object. The source code is
441 returned as a single string. An :exc:`IOError` is raised if the source code
442 cannot be retrieved.
443
444
Georg Brandl7be19aa2008-06-07 15:59:10 +0000445.. function:: cleandoc(doc)
446
447 Clean up indentation from docstrings that are indented to line up with blocks
Senthil Kumaran739b3732016-05-29 20:38:55 -0700448 of code.
449
450 All leading whitespace is removed from the first line. Any leading whitespace
451 that can be uniformly removed from the second line onwards is removed. Empty
452 lines at the beginning and end are subsequently removed. Also, all tabs are
453 expanded to spaces.
Georg Brandl7be19aa2008-06-07 15:59:10 +0000454
455 .. versionadded:: 2.6
456
457
Georg Brandl8ec7f652007-08-15 14:28:01 +0000458.. _inspect-classes-functions:
459
460Classes and functions
461---------------------
462
463
464.. function:: getclasstree(classes[, unique])
465
466 Arrange the given list of classes into a hierarchy of nested lists. Where a
467 nested list appears, it contains classes derived from the class whose entry
468 immediately precedes the list. Each entry is a 2-tuple containing a class and a
469 tuple of its base classes. If the *unique* argument is true, exactly one entry
470 appears in the returned structure for each class in the given list. Otherwise,
471 classes using multiple inheritance and their descendants will appear multiple
472 times.
473
474
475.. function:: getargspec(func)
476
Georg Brandlcbb2e492011-01-09 08:04:37 +0000477 Get the names and default values of a Python function's arguments. A tuple of
478 four things is returned: ``(args, varargs, keywords, defaults)``. *args* is a
479 list of the argument names (it may contain nested lists). *varargs* and
480 *keywords* are the names of the ``*`` and ``**`` arguments or
481 ``None``. *defaults* is a tuple of default argument values or None if there
482 are no default arguments; if this tuple has *n* elements, they correspond to
483 the last *n* elements listed in *args*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000484
Georg Brandle3c3db52008-01-11 09:55:53 +0000485 .. versionchanged:: 2.6
486 Returns a :term:`named tuple` ``ArgSpec(args, varargs, keywords,
487 defaults)``.
488
Georg Brandl8ec7f652007-08-15 14:28:01 +0000489
490.. function:: getargvalues(frame)
491
Georg Brandlcbb2e492011-01-09 08:04:37 +0000492 Get information about arguments passed into a particular frame. A tuple of
493 four things is returned: ``(args, varargs, keywords, locals)``. *args* is a
494 list of the argument names (it may contain nested lists). *varargs* and
495 *keywords* are the names of the ``*`` and ``**`` arguments or ``None``.
496 *locals* is the locals dictionary of the given frame.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000497
Georg Brandle3c3db52008-01-11 09:55:53 +0000498 .. versionchanged:: 2.6
499 Returns a :term:`named tuple` ``ArgInfo(args, varargs, keywords,
500 locals)``.
501
Georg Brandl8ec7f652007-08-15 14:28:01 +0000502
503.. function:: formatargspec(args[, varargs, varkw, defaults, formatarg, formatvarargs, formatvarkw, formatvalue, join])
504
505 Format a pretty argument spec from the four values returned by
506 :func:`getargspec`. The format\* arguments are the corresponding optional
507 formatting functions that are called to turn names and values into strings.
508
509
510.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue, join])
511
512 Format a pretty argument spec from the four values returned by
513 :func:`getargvalues`. The format\* arguments are the corresponding optional
514 formatting functions that are called to turn names and values into strings.
515
516
517.. function:: getmro(cls)
518
519 Return a tuple of class cls's base classes, including cls, in method resolution
520 order. No class appears more than once in this tuple. Note that the method
521 resolution order depends on cls's type. Unless a very peculiar user-defined
522 metatype is in use, cls will be the first element of the tuple.
523
524
Benjamin Peterson7e213252010-03-30 17:58:13 +0000525.. function:: getcallargs(func[, *args][, **kwds])
526
527 Bind the *args* and *kwds* to the argument names of the Python function or
528 method *func*, as if it was called with them. For bound methods, bind also the
529 first argument (typically named ``self``) to the associated instance. A dict
530 is returned, mapping the argument names (including the names of the ``*`` and
531 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
532 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
533 an exception because of incompatible signature, an exception of the same type
534 and the same or similar message is raised. For example::
535
536 >>> from inspect import getcallargs
537 >>> def f(a, b=1, *pos, **named):
538 ... pass
539 >>> getcallargs(f, 1, 2, 3)
540 {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
541 >>> getcallargs(f, a=2, x=4)
542 {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
543 >>> getcallargs(f)
544 Traceback (most recent call last):
545 ...
546 TypeError: f() takes at least 1 argument (0 given)
547
548 .. versionadded:: 2.7
549
550
Georg Brandl8ec7f652007-08-15 14:28:01 +0000551.. _inspect-stack:
552
553The interpreter stack
554---------------------
555
556When the following functions return "frame records," each record is a tuple of
557six items: the frame object, the filename, the line number of the current line,
558the function name, a list of lines of context from the source code, and the
559index of the current line within that list.
560
Georg Brandl16a57f62009-04-27 15:29:09 +0000561.. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000562
563 Keeping references to frame objects, as found in the first element of the frame
564 records these functions return, can cause your program to create reference
565 cycles. Once a reference cycle has been created, the lifespan of all objects
566 which can be accessed from the objects which form the cycle can become much
567 longer even if Python's optional cycle detector is enabled. If such cycles must
568 be created, it is important to ensure they are explicitly broken to avoid the
569 delayed destruction of objects and increased memory consumption which occurs.
570
571 Though the cycle detector will catch these, destruction of the frames (and local
572 variables) can be made deterministic by removing the cycle in a
573 :keyword:`finally` clause. This is also important if the cycle detector was
574 disabled when Python was compiled or using :func:`gc.disable`. For example::
575
576 def handle_stackframe_without_leak():
577 frame = inspect.currentframe()
578 try:
579 # do something with the frame
580 finally:
581 del frame
582
583The optional *context* argument supported by most of these functions specifies
584the number of lines of context to return, which are centered around the current
585line.
586
587
588.. function:: getframeinfo(frame[, context])
589
590 Get information about a frame or traceback object. A 5-tuple is returned, the
591 last five elements of the frame's frame record.
592
Georg Brandle3c3db52008-01-11 09:55:53 +0000593 .. versionchanged:: 2.6
594 Returns a :term:`named tuple` ``Traceback(filename, lineno, function,
595 code_context, index)``.
596
Georg Brandl8ec7f652007-08-15 14:28:01 +0000597
598.. function:: getouterframes(frame[, context])
599
600 Get a list of frame records for a frame and all outer frames. These frames
601 represent the calls that lead to the creation of *frame*. The first entry in the
602 returned list represents *frame*; the last entry represents the outermost call
603 on *frame*'s stack.
604
605
606.. function:: getinnerframes(traceback[, context])
607
608 Get a list of frame records for a traceback's frame and all inner frames. These
609 frames represent calls made as a consequence of *frame*. The first entry in the
610 list represents *traceback*; the last entry represents where the exception was
611 raised.
612
613
614.. function:: currentframe()
615
616 Return the frame object for the caller's stack frame.
617
Georg Brandl6c14e582009-10-22 11:48:10 +0000618 .. impl-detail::
619
620 This function relies on Python stack frame support in the interpreter,
621 which isn't guaranteed to exist in all implementations of Python. If
622 running in an implementation without Python stack frame support this
623 function returns ``None``.
Michael Foord668be582009-09-13 16:46:19 +0000624
Georg Brandl8ec7f652007-08-15 14:28:01 +0000625
626.. function:: stack([context])
627
628 Return a list of frame records for the caller's stack. The first entry in the
629 returned list represents the caller; the last entry represents the outermost
630 call on the stack.
631
632
633.. function:: trace([context])
634
635 Return a list of frame records for the stack between the current frame and the
636 frame in which an exception currently being handled was raised in. The first
637 entry in the list represents the caller; the last entry represents where the
638 exception was raised.
639