blob: 50d59e11565357592d92cc293aa322945f8fde92 [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
338 ``int.__add__``. An object passing this test has a :attr:`__get__` attribute
339 but not a :attr:`__set__` attribute, but beyond that the set of attributes
340 varies. :attr:`__name__` is usually sensible, and :attr:`__doc__` often is.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000341
Georg Brandl5c174bb2007-10-21 10:32:54 +0000342 Methods implemented via descriptors that also pass one of the other tests
343 return false from the :func:`ismethoddescriptor` test, simply because the
344 other tests promise more -- you can, e.g., count on having the
345 :attr:`im_func` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000346
347
348.. function:: isdatadescriptor(object)
349
350 Return true if the object is a data descriptor.
351
Georg Brandl5c174bb2007-10-21 10:32:54 +0000352 Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute.
353 Examples are properties (defined in Python), getsets, and members. The
354 latter two are defined in C and there are more specific tests available for
355 those types, which is robust across Python implementations. Typically, data
356 descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes
357 (properties, getsets, and members have both of these attributes), but this is
358 not guaranteed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000359
360 .. versionadded:: 2.3
361
362
363.. function:: isgetsetdescriptor(object)
364
365 Return true if the object is a getset descriptor.
366
Georg Brandl6c14e582009-10-22 11:48:10 +0000367 .. impl-detail::
368
369 getsets are attributes defined in extension modules via
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100370 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl6c14e582009-10-22 11:48:10 +0000371 types, this method will always return ``False``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000372
373 .. versionadded:: 2.5
374
375
376.. function:: ismemberdescriptor(object)
377
378 Return true if the object is a member descriptor.
379
Georg Brandl6c14e582009-10-22 11:48:10 +0000380 .. impl-detail::
381
382 Member descriptors are attributes defined in extension modules via
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100383 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl6c14e582009-10-22 11:48:10 +0000384 types, this method will always return ``False``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000385
386 .. versionadded:: 2.5
387
388
389.. _inspect-source:
390
391Retrieving source code
392----------------------
393
Georg Brandl8ec7f652007-08-15 14:28:01 +0000394.. function:: getdoc(object)
395
Georg Brandl7be19aa2008-06-07 15:59:10 +0000396 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000397
398
399.. function:: getcomments(object)
400
401 Return in a single string any lines of comments immediately preceding the
402 object's source code (for a class, function, or method), or at the top of the
403 Python source file (if the object is a module).
404
405
406.. function:: getfile(object)
407
408 Return the name of the (text or binary) file in which an object was defined.
409 This will fail with a :exc:`TypeError` if the object is a built-in module,
410 class, or function.
411
412
413.. function:: getmodule(object)
414
415 Try to guess which module an object was defined in.
416
417
418.. function:: getsourcefile(object)
419
420 Return the name of the Python source file in which an object was defined. This
421 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
422 function.
423
424
425.. function:: getsourcelines(object)
426
427 Return a list of source lines and starting line number for an object. The
428 argument may be a module, class, method, function, traceback, frame, or code
429 object. The source code is returned as a list of the lines corresponding to the
430 object and the line number indicates where in the original source file the first
431 line of code was found. An :exc:`IOError` is raised if the source code cannot
432 be retrieved.
433
434
435.. function:: getsource(object)
436
437 Return the text of the source code for an object. The argument may be a module,
438 class, method, function, traceback, frame, or code object. The source code is
439 returned as a single string. An :exc:`IOError` is raised if the source code
440 cannot be retrieved.
441
442
Georg Brandl7be19aa2008-06-07 15:59:10 +0000443.. function:: cleandoc(doc)
444
445 Clean up indentation from docstrings that are indented to line up with blocks
446 of code. Any whitespace that can be uniformly removed from the second line
447 onwards is removed. Also, all tabs are expanded to spaces.
448
449 .. versionadded:: 2.6
450
451
Georg Brandl8ec7f652007-08-15 14:28:01 +0000452.. _inspect-classes-functions:
453
454Classes and functions
455---------------------
456
457
458.. function:: getclasstree(classes[, unique])
459
460 Arrange the given list of classes into a hierarchy of nested lists. Where a
461 nested list appears, it contains classes derived from the class whose entry
462 immediately precedes the list. Each entry is a 2-tuple containing a class and a
463 tuple of its base classes. If the *unique* argument is true, exactly one entry
464 appears in the returned structure for each class in the given list. Otherwise,
465 classes using multiple inheritance and their descendants will appear multiple
466 times.
467
468
469.. function:: getargspec(func)
470
Georg Brandlcbb2e492011-01-09 08:04:37 +0000471 Get the names and default values of a Python function's arguments. A tuple of
472 four things is returned: ``(args, varargs, keywords, defaults)``. *args* is a
473 list of the argument names (it may contain nested lists). *varargs* and
474 *keywords* are the names of the ``*`` and ``**`` arguments or
475 ``None``. *defaults* is a tuple of default argument values or None if there
476 are no default arguments; if this tuple has *n* elements, they correspond to
477 the last *n* elements listed in *args*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000478
Georg Brandle3c3db52008-01-11 09:55:53 +0000479 .. versionchanged:: 2.6
480 Returns a :term:`named tuple` ``ArgSpec(args, varargs, keywords,
481 defaults)``.
482
Georg Brandl8ec7f652007-08-15 14:28:01 +0000483
484.. function:: getargvalues(frame)
485
Georg Brandlcbb2e492011-01-09 08:04:37 +0000486 Get information about arguments passed into a particular frame. A tuple of
487 four things is returned: ``(args, varargs, keywords, locals)``. *args* is a
488 list of the argument names (it may contain nested lists). *varargs* and
489 *keywords* are the names of the ``*`` and ``**`` arguments or ``None``.
490 *locals* is the locals dictionary of the given frame.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000491
Georg Brandle3c3db52008-01-11 09:55:53 +0000492 .. versionchanged:: 2.6
493 Returns a :term:`named tuple` ``ArgInfo(args, varargs, keywords,
494 locals)``.
495
Georg Brandl8ec7f652007-08-15 14:28:01 +0000496
497.. function:: formatargspec(args[, varargs, varkw, defaults, formatarg, formatvarargs, formatvarkw, formatvalue, join])
498
499 Format a pretty argument spec from the four values returned by
500 :func:`getargspec`. The format\* arguments are the corresponding optional
501 formatting functions that are called to turn names and values into strings.
502
503
504.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue, join])
505
506 Format a pretty argument spec from the four values returned by
507 :func:`getargvalues`. The format\* arguments are the corresponding optional
508 formatting functions that are called to turn names and values into strings.
509
510
511.. function:: getmro(cls)
512
513 Return a tuple of class cls's base classes, including cls, in method resolution
514 order. No class appears more than once in this tuple. Note that the method
515 resolution order depends on cls's type. Unless a very peculiar user-defined
516 metatype is in use, cls will be the first element of the tuple.
517
518
Benjamin Peterson7e213252010-03-30 17:58:13 +0000519.. function:: getcallargs(func[, *args][, **kwds])
520
521 Bind the *args* and *kwds* to the argument names of the Python function or
522 method *func*, as if it was called with them. For bound methods, bind also the
523 first argument (typically named ``self``) to the associated instance. A dict
524 is returned, mapping the argument names (including the names of the ``*`` and
525 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
526 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
527 an exception because of incompatible signature, an exception of the same type
528 and the same or similar message is raised. For example::
529
530 >>> from inspect import getcallargs
531 >>> def f(a, b=1, *pos, **named):
532 ... pass
533 >>> getcallargs(f, 1, 2, 3)
534 {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
535 >>> getcallargs(f, a=2, x=4)
536 {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
537 >>> getcallargs(f)
538 Traceback (most recent call last):
539 ...
540 TypeError: f() takes at least 1 argument (0 given)
541
542 .. versionadded:: 2.7
543
544
Georg Brandl8ec7f652007-08-15 14:28:01 +0000545.. _inspect-stack:
546
547The interpreter stack
548---------------------
549
550When the following functions return "frame records," each record is a tuple of
551six items: the frame object, the filename, the line number of the current line,
552the function name, a list of lines of context from the source code, and the
553index of the current line within that list.
554
Georg Brandl16a57f62009-04-27 15:29:09 +0000555.. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000556
557 Keeping references to frame objects, as found in the first element of the frame
558 records these functions return, can cause your program to create reference
559 cycles. Once a reference cycle has been created, the lifespan of all objects
560 which can be accessed from the objects which form the cycle can become much
561 longer even if Python's optional cycle detector is enabled. If such cycles must
562 be created, it is important to ensure they are explicitly broken to avoid the
563 delayed destruction of objects and increased memory consumption which occurs.
564
565 Though the cycle detector will catch these, destruction of the frames (and local
566 variables) can be made deterministic by removing the cycle in a
567 :keyword:`finally` clause. This is also important if the cycle detector was
568 disabled when Python was compiled or using :func:`gc.disable`. For example::
569
570 def handle_stackframe_without_leak():
571 frame = inspect.currentframe()
572 try:
573 # do something with the frame
574 finally:
575 del frame
576
577The optional *context* argument supported by most of these functions specifies
578the number of lines of context to return, which are centered around the current
579line.
580
581
582.. function:: getframeinfo(frame[, context])
583
584 Get information about a frame or traceback object. A 5-tuple is returned, the
585 last five elements of the frame's frame record.
586
Georg Brandle3c3db52008-01-11 09:55:53 +0000587 .. versionchanged:: 2.6
588 Returns a :term:`named tuple` ``Traceback(filename, lineno, function,
589 code_context, index)``.
590
Georg Brandl8ec7f652007-08-15 14:28:01 +0000591
592.. function:: getouterframes(frame[, context])
593
594 Get a list of frame records for a frame and all outer frames. These frames
595 represent the calls that lead to the creation of *frame*. The first entry in the
596 returned list represents *frame*; the last entry represents the outermost call
597 on *frame*'s stack.
598
599
600.. function:: getinnerframes(traceback[, context])
601
602 Get a list of frame records for a traceback's frame and all inner frames. These
603 frames represent calls made as a consequence of *frame*. The first entry in the
604 list represents *traceback*; the last entry represents where the exception was
605 raised.
606
607
608.. function:: currentframe()
609
610 Return the frame object for the caller's stack frame.
611
Georg Brandl6c14e582009-10-22 11:48:10 +0000612 .. impl-detail::
613
614 This function relies on Python stack frame support in the interpreter,
615 which isn't guaranteed to exist in all implementations of Python. If
616 running in an implementation without Python stack frame support this
617 function returns ``None``.
Michael Foord668be582009-09-13 16:46:19 +0000618
Georg Brandl8ec7f652007-08-15 14:28:01 +0000619
620.. function:: stack([context])
621
622 Return a list of frame records for the caller's stack. The first entry in the
623 returned list represents the caller; the last entry represents the outermost
624 call on the stack.
625
626
627.. function:: trace([context])
628
629 Return a list of frame records for the stack between the current frame and the
630 frame in which an exception currently being handled was raised in. The first
631 entry in the list represents the caller; the last entry represents where the
632 exception was raised.
633