Debian Codegraph @

Doc/library/inspect.rst

raw
1 :mod:`!inspect` --- Inspect live objects
2 ========================================
3
4 .. testsetup:: *
5
6 import inspect
7 from inspect import *
8
9 .. module:: inspect
10 :synopsis: Extract information and source code from live objects.
11
12 .. moduleauthor:: Ka-Ping Yee <[email protected]>
13 .. sectionauthor:: Ka-Ping Yee <[email protected]>
14
15 **Source code:** :source:`Lib/inspect.py`
16
17 --------------
18
19 The :mod:`inspect` module provides several useful functions to help get
20 information about live objects such as modules, classes, methods, functions,
21 tracebacks, frame objects, and code objects. For example, it can help you
22 examine the contents of a class, retrieve the source code of a method, extract
23 and format the argument list for a function, or get all the information you need
24 to display a detailed traceback.
25
26 There are four main kinds of services provided by this module: type checking,
27 getting source code, inspecting classes and functions, and examining the
28 interpreter stack.
29
30
31 .. _inspect-types:
32
33 Types and members
34 -----------------
35
36 The :func:`getmembers` function retrieves the members of an object such as a
37 class or module. The functions whose names begin with "is" are mainly
38 provided as convenient choices for the second argument to :func:`getmembers`.
39 They also help you determine when you can expect to find the following special
40 attributes (see :ref:`import-mod-attrs` for module attributes):
41
42 .. this function name is too big to fit in the ascii-art table below
43 .. |coroutine-origin-link| replace:: :func:`sys.set_coroutine_origin_tracking_depth`
44
45 +-----------------+-------------------+---------------------------+
46 | Type | Attribute | Description |
47 +=================+===================+===========================+
48 | class | __doc__ | documentation string |
49 +-----------------+-------------------+---------------------------+
50 | | __name__ | name with which this |
51 | | | class was defined |
52 +-----------------+-------------------+---------------------------+
53 | | __qualname__ | qualified name |
54 +-----------------+-------------------+---------------------------+
55 | | __module__ | name of module in which |
56 | | | this class was defined |
57 +-----------------+-------------------+---------------------------+
58 | | __type_params__ | A tuple containing the |
59 | | | :ref:`type parameters |
60 | | | <type-params>` of |
61 | | | a generic class |
62 +-----------------+-------------------+---------------------------+
63 | method | __doc__ | documentation string |
64 +-----------------+-------------------+---------------------------+
65 | | __name__ | name with which this |
66 | | | method was defined |
67 +-----------------+-------------------+---------------------------+
68 | | __qualname__ | qualified name |
69 +-----------------+-------------------+---------------------------+
70 | | __func__ | function object |
71 | | | containing implementation |
72 | | | of method |
73 +-----------------+-------------------+---------------------------+
74 | | __self__ | instance to which this |
75 | | | method is bound, or |
76 | | | ``None`` |
77 +-----------------+-------------------+---------------------------+
78 | | __module__ | name of module in which |
79 | | | this method was defined |
80 +-----------------+-------------------+---------------------------+
81 | function | __doc__ | documentation string |
82 +-----------------+-------------------+---------------------------+
83 | | __name__ | name with which this |
84 | | | function was defined |
85 +-----------------+-------------------+---------------------------+
86 | | __qualname__ | qualified name |
87 +-----------------+-------------------+---------------------------+
88 | | __code__ | code object containing |
89 | | | compiled function |
90 | | | :term:`bytecode` |
91 +-----------------+-------------------+---------------------------+
92 | | __defaults__ | tuple of any default |
93 | | | values for positional or |
94 | | | keyword parameters |
95 +-----------------+-------------------+---------------------------+
96 | | __kwdefaults__ | mapping of any default |
97 | | | values for keyword-only |
98 | | | parameters |
99 +-----------------+-------------------+---------------------------+
100 | | __globals__ | global namespace in which |
101 | | | this function was defined |
102 +-----------------+-------------------+---------------------------+
103 | | __builtins__ | builtins namespace |
104 +-----------------+-------------------+---------------------------+
105 | | __annotations__ | mapping of parameters |
106 | | | names to annotations; |
107 | | | ``"return"`` key is |
108 | | | reserved for return |
109 | | | annotations. |
110 +-----------------+-------------------+---------------------------+
111 | | __type_params__ | A tuple containing the |
112 | | | :ref:`type parameters |
113 | | | <type-params>` of |
114 | | | a generic function |
115 +-----------------+-------------------+---------------------------+
116 | | __module__ | name of module in which |
117 | | | this function was defined |
118 +-----------------+-------------------+---------------------------+
119 | traceback | tb_frame | frame object at this |
120 | | | level |
121 +-----------------+-------------------+---------------------------+
122 | | tb_lasti | index of last attempted |
123 | | | instruction in bytecode |
124 +-----------------+-------------------+---------------------------+
125 | | tb_lineno | current line number in |
126 | | | Python source code |
127 +-----------------+-------------------+---------------------------+
128 | | tb_next | next inner traceback |
129 | | | object (called by this |
130 | | | level) |
131 +-----------------+-------------------+---------------------------+
132 | frame | f_back | next outer frame object |
133 | | | (this frame's caller) |
134 +-----------------+-------------------+---------------------------+
135 | | f_builtins | builtins namespace seen |
136 | | | by this frame |
137 +-----------------+-------------------+---------------------------+
138 | | f_code | code object being |
139 | | | executed in this frame |
140 +-----------------+-------------------+---------------------------+
141 | | f_globals | global namespace seen by |
142 | | | this frame |
143 +-----------------+-------------------+---------------------------+
144 | | f_lasti | index of last attempted |
145 | | | instruction in bytecode |
146 +-----------------+-------------------+---------------------------+
147 | | f_lineno | current line number in |
148 | | | Python source code |
149 +-----------------+-------------------+---------------------------+
150 | | f_locals | local namespace seen by |
151 | | | this frame |
152 +-----------------+-------------------+---------------------------+
153 | | f_trace | tracing function for this |
154 | | | frame, or ``None`` |
155 +-----------------+-------------------+---------------------------+
156 | code | co_argcount | number of arguments (not |
157 | | | including keyword only |
158 | | | arguments, \* or \*\* |
159 | | | args) |
160 +-----------------+-------------------+---------------------------+
161 | | co_code | string of raw compiled |
162 | | | bytecode |
163 +-----------------+-------------------+---------------------------+
164 | | co_cellvars | tuple of names of cell |
165 | | | variables (referenced by |
166 | | | containing scopes) |
167 +-----------------+-------------------+---------------------------+
168 | | co_consts | tuple of constants used |
169 | | | in the bytecode |
170 +-----------------+-------------------+---------------------------+
171 | | co_filename | name of file in which |
172 | | | this code object was |
173 | | | created |
174 +-----------------+-------------------+---------------------------+
175 | | co_firstlineno | number of first line in |
176 | | | Python source code |
177 +-----------------+-------------------+---------------------------+
178 | | co_flags | bitmap of ``CO_*`` flags, |
179 | | | read more :ref:`here |
180 | | | <inspect-module-co-flags>`|
181 +-----------------+-------------------+---------------------------+
182 | | co_lnotab | encoded mapping of line |
183 | | | numbers to bytecode |
184 | | | indices |
185 +-----------------+-------------------+---------------------------+
186 | | co_freevars | tuple of names of free |
187 | | | variables (referenced via |
188 | | | a function's closure) |
189 +-----------------+-------------------+---------------------------+
190 | | co_posonlyargcount| number of positional only |
191 | | | arguments |
192 +-----------------+-------------------+---------------------------+
193 | | co_kwonlyargcount | number of keyword only |
194 | | | arguments (not including |
195 | | | \*\* arg) |
196 +-----------------+-------------------+---------------------------+
197 | | co_name | name with which this code |
198 | | | object was defined |
199 +-----------------+-------------------+---------------------------+
200 | | co_qualname | fully qualified name with |
201 | | | which this code object |
202 | | | was defined |
203 +-----------------+-------------------+---------------------------+
204 | | co_names | tuple of names other |
205 | | | than arguments and |
206 | | | function locals |
207 +-----------------+-------------------+---------------------------+
208 | | co_nlocals | number of local variables |
209 +-----------------+-------------------+---------------------------+
210 | | co_stacksize | virtual machine stack |
211 | | | space required |
212 +-----------------+-------------------+---------------------------+
213 | | co_varnames | tuple of names of |
214 | | | arguments and local |
215 | | | variables |
216 +-----------------+-------------------+---------------------------+
217 | generator | __name__ | name |
218 +-----------------+-------------------+---------------------------+
219 | | __qualname__ | qualified name |
220 +-----------------+-------------------+---------------------------+
221 | | gi_frame | frame |
222 +-----------------+-------------------+---------------------------+
223 | | gi_running | is the generator running? |
224 +-----------------+-------------------+---------------------------+
225 | | gi_suspended | is the generator |
226 | | | suspended? |
227 +-----------------+-------------------+---------------------------+
228 | | gi_code | code |
229 +-----------------+-------------------+---------------------------+
230 | | gi_yieldfrom | object being iterated by |
231 | | | ``yield from``, or |
232 | | | ``None`` |
233 +-----------------+-------------------+---------------------------+
234 | async generator | __name__ | name |
235 +-----------------+-------------------+---------------------------+
236 | | __qualname__ | qualified name |
237 +-----------------+-------------------+---------------------------+
238 | | ag_await | object being awaited on, |
239 | | | or ``None`` |
240 +-----------------+-------------------+---------------------------+
241 | | ag_frame | frame |
242 +-----------------+-------------------+---------------------------+
243 | | ag_running | is the generator running? |
244 +-----------------+-------------------+---------------------------+
245 | | ag_suspended | is the generator |
246 | | | suspended? |
247 +-----------------+-------------------+---------------------------+
248 | | ag_code | code |
249 +-----------------+-------------------+---------------------------+
250 | coroutine | __name__ | name |
251 +-----------------+-------------------+---------------------------+
252 | | __qualname__ | qualified name |
253 +-----------------+-------------------+---------------------------+
254 | | cr_await | object being awaited on, |
255 | | | or ``None`` |
256 +-----------------+-------------------+---------------------------+
257 | | cr_frame | frame |
258 +-----------------+-------------------+---------------------------+
259 | | cr_running | is the coroutine running? |
260 +-----------------+-------------------+---------------------------+
261 | | cr_suspended | is the coroutine |
262 | | | suspended? |
263 +-----------------+-------------------+---------------------------+
264 | | cr_code | code |
265 +-----------------+-------------------+---------------------------+
266 | | cr_origin | where coroutine was |
267 | | | created, or ``None``. See |
268 | | | |coroutine-origin-link| |
269 +-----------------+-------------------+---------------------------+
270 | builtin | __doc__ | documentation string |
271 +-----------------+-------------------+---------------------------+
272 | | __name__ | original name of this |
273 | | | function or method |
274 +-----------------+-------------------+---------------------------+
275 | | __qualname__ | qualified name |
276 +-----------------+-------------------+---------------------------+
277 | | __self__ | instance to which a |
278 | | | method is bound, or |
279 | | | ``None`` |
280 +-----------------+-------------------+---------------------------+
281
282 .. versionchanged:: 3.5
283
284 Add ``__qualname__`` and ``gi_yieldfrom`` attributes to generators.
285
286 The ``__name__`` attribute of generators is now set from the function
287 name, instead of the code name, and it can now be modified.
288
289 .. versionchanged:: 3.7
290
291 Add ``cr_origin`` attribute to coroutines.
292
293 .. versionchanged:: 3.10
294
295 Add ``__builtins__`` attribute to functions.
296
297 .. versionchanged:: 3.11
298
299 Add ``gi_suspended`` attribute to generators.
300
301 .. versionchanged:: 3.11
302
303 Add ``cr_suspended`` attribute to coroutines.
304
305 .. versionchanged:: 3.12
306
307 Add ``ag_suspended`` attribute to async generators.
308
309
310 .. function:: getmembers(object[, predicate])
311
312 Return all the members of an object in a list of ``(name, value)``
313 pairs sorted by name. If the optional *predicate* argument—which will be
314 called with the ``value`` object of each member—is supplied, only members
315 for which the predicate returns a true value are included.
316
317 .. note::
318
319 :func:`getmembers` will only return class attributes defined in the
320 metaclass when the argument is a class and those attributes have been
321 listed in the metaclass' custom :meth:`~object.__dir__`.
322
323
324 .. function:: getmembers_static(object[, predicate])
325
326 Return all the members of an object in a list of ``(name, value)``
327 pairs sorted by name without triggering dynamic lookup via the descriptor
328 protocol, __getattr__ or __getattribute__. Optionally, only return members
329 that satisfy a given predicate.
330
331 .. note::
332
333 :func:`getmembers_static` may not be able to retrieve all members
334 that getmembers can fetch (like dynamically created attributes)
335 and may find members that getmembers can't (like descriptors
336 that raise AttributeError). It can also return descriptor objects
337 instead of instance members in some cases.
338
339 .. versionadded:: 3.11
340
341
342 .. function:: getmodulename(path)
343
344 Return the name of the module named by the file *path*, without including the
345 names of enclosing packages. The file extension is checked against all of
346 the entries in :func:`importlib.machinery.all_suffixes`. If it matches,
347 the final path component is returned with the extension removed.
348 Otherwise, ``None`` is returned.
349
350 Note that this function *only* returns a meaningful name for actual
351 Python modules - paths that potentially refer to Python packages will
352 still return ``None``.
353
354 .. versionchanged:: 3.3
355 The function is based directly on :mod:`importlib`.
356
357
358 .. function:: ismodule(object)
359
360 Return ``True`` if the object is a module.
361
362
363 .. function:: isclass(object)
364
365 Return ``True`` if the object is a class, whether built-in or created in Python
366 code.
367
368 This function returns ``False`` for :ref:`generic aliases <types-genericalias>` of classes,
369 such as ``list[int]``.
370
371
372 .. function:: ismethod(object)
373
374 Return ``True`` if the object is a bound method written in Python.
375
376
377 .. function:: isfunction(object)
378
379 Return ``True`` if the object is a Python function, which includes functions
380 created by a :term:`lambda` expression.
381
382
383 .. function:: isgeneratorfunction(object)
384
385 Return ``True`` if the object is a Python generator function.
386
387 .. versionchanged:: 3.8
388 Functions wrapped in :func:`functools.partial` now return ``True`` if the
389 wrapped function is a Python generator function.
390
391 .. versionchanged:: 3.13
392 Functions wrapped in :func:`functools.partialmethod` now return ``True``
393 if the wrapped function is a Python generator function.
394
395 .. function:: isgenerator(object)
396
397 Return ``True`` if the object is a generator.
398
399
400 .. function:: iscoroutinefunction(object)
401
402 Return ``True`` if the object is a :term:`coroutine function` (a function
403 defined with an :keyword:`async def` syntax), a :func:`functools.partial`
404 wrapping a :term:`coroutine function`, or a sync function marked with
405 :func:`markcoroutinefunction`.
406
407 .. versionadded:: 3.5
408
409 .. versionchanged:: 3.8
410 Functions wrapped in :func:`functools.partial` now return ``True`` if the
411 wrapped function is a :term:`coroutine function`.
412
413 .. versionchanged:: 3.12
414 Sync functions marked with :func:`markcoroutinefunction` now return
415 ``True``.
416
417 .. versionchanged:: 3.13
418 Functions wrapped in :func:`functools.partialmethod` now return ``True``
419 if the wrapped function is a :term:`coroutine function`.
420
421
422 .. function:: markcoroutinefunction(func)
423
424 Decorator to mark a callable as a :term:`coroutine function` if it would not
425 otherwise be detected by :func:`iscoroutinefunction`.
426
427 This may be of use for sync functions that return a :term:`coroutine`, if
428 the function is passed to an API that requires :func:`iscoroutinefunction`.
429
430 When possible, using an :keyword:`async def` function is preferred. Also
431 acceptable is calling the function and testing the return with
432 :func:`iscoroutine`.
433
434 .. versionadded:: 3.12
435
436
437 .. function:: iscoroutine(object)
438
439 Return ``True`` if the object is a :term:`coroutine` created by an
440 :keyword:`async def` function.
441
442 .. versionadded:: 3.5
443
444
445 .. function:: isawaitable(object)
446
447 Return ``True`` if the object can be used in :keyword:`await` expression.
448
449 Can also be used to distinguish generator-based coroutines from regular
450 generators:
451
452 .. testcode::
453
454 import types
455
456 def gen():
457 yield
458 @types.coroutine
459 def gen_coro():
460 yield
461
462 assert not isawaitable(gen())
463 assert isawaitable(gen_coro())
464
465 .. versionadded:: 3.5
466
467
468 .. function:: isasyncgenfunction(object)
469
470 Return ``True`` if the object is an :term:`asynchronous generator` function,
471 for example:
472
473 .. doctest::
474
475 >>> async def agen():
476 ... yield 1
477 ...
478 >>> inspect.isasyncgenfunction(agen)
479 True
480
481 .. versionadded:: 3.6
482
483 .. versionchanged:: 3.8
484 Functions wrapped in :func:`functools.partial` now return ``True`` if the
485 wrapped function is an :term:`asynchronous generator` function.
486
487 .. versionchanged:: 3.13
488 Functions wrapped in :func:`functools.partialmethod` now return ``True``
489 if the wrapped function is a :term:`asynchronous generator` function.
490
491 .. function:: isasyncgen(object)
492
493 Return ``True`` if the object is an :term:`asynchronous generator iterator`
494 created by an :term:`asynchronous generator` function.
495
496 .. versionadded:: 3.6
497
498 .. function:: istraceback(object)
499
500 Return ``True`` if the object is a traceback.
501
502
503 .. function:: isframe(object)
504
505 Return ``True`` if the object is a frame.
506
507
508 .. function:: iscode(object)
509
510 Return ``True`` if the object is a code.
511
512
513 .. function:: isbuiltin(object)
514
515 Return ``True`` if the object is a built-in function or a bound built-in method.
516
517
518 .. function:: ismethodwrapper(object)
519
520 Return ``True`` if the type of object is a :class:`~types.MethodWrapperType`.
521
522 These are instances of :class:`~types.MethodWrapperType`, such as :meth:`~object.__str__`,
523 :meth:`~object.__eq__` and :meth:`~object.__repr__`.
524
525 .. versionadded:: 3.11
526
527
528 .. function:: isroutine(object)
529
530 Return ``True`` if the object is a user-defined or built-in function or method.
531
532
533 .. function:: isabstract(object)
534
535 Return ``True`` if the object is an abstract base class.
536
537
538 .. function:: ismethoddescriptor(object)
539
540 Return ``True`` if the object is a method descriptor, but not if
541 :func:`isclass`, :func:`ismethod` or :func:`isfunction` is true.
542
543 This, for example, is true of ``int.__add__``. An object passing this test
544 has a :meth:`~object.__get__` method, but not a :meth:`~object.__set__`
545 method or a :meth:`~object.__delete__` method. Beyond that, the set of
546 attributes varies. A :attr:`~definition.__name__` attribute is usually
547 sensible, and :attr:`~definition.__doc__` often is.
548
549 Method descriptors that also pass any of the other tests (:func:`!isclass`,
550 :func:`!ismethod` or :func:`!isfunction`) make this function return ``False``,
551 simply because those other tests promise more -- you can, for example, count
552 on having the :attr:`~method.__func__` attribute when an object passes
553 :func:`ismethod`.
554
555 .. versionchanged:: 3.13
556 This function no longer incorrectly reports objects with :meth:`~object.__get__`
557 and :meth:`~object.__delete__`, but not :meth:`~object.__set__`, as being method
558 descriptors (such objects are data descriptors, not method descriptors).
559
560
561 .. function:: isdatadescriptor(object)
562
563 Return ``True`` if the object is a data descriptor, but not if
564 :func:`isclass`, :func:`ismethod` or :func:`isfunction` is true.
565
566 Data descriptors always have a :meth:`~object.__set__` method and/or
567 a :meth:`~object.__delete__` method. Optionally, they may also have a
568 :meth:`~object.__get__` method.
569
570 Examples of data descriptors are :func:`properties <property>`, getsets and
571 member descriptors. Note that for the latter two (defined only in C extension
572 modules), more specific tests are available: :func:`isgetsetdescriptor` and
573 :func:`ismemberdescriptor`, respectively.
574
575 While data descriptors may also have :attr:`~definition.__name__` and
576 :attr:`!__doc__` attributes (as properties, getsets and member descriptors
577 do), this is not necessarily the case in general.
578
579 .. versionchanged:: 3.8
580 This function now reports objects with only a :meth:`~object.__set__` method
581 as being data descriptors (the presence of :meth:`~object.__get__` is no
582 longer required for that). Moreover, objects with :meth:`~object.__delete__`,
583 but not :meth:`~object.__set__`, are now properly recognized as data
584 descriptors as well, which was not the case previously.
585
586 .. function:: isgetsetdescriptor(object)
587
588 Return ``True`` if the object is a getset descriptor.
589
590 .. impl-detail::
591
592 getsets are attributes defined in extension modules via
593 :c:type:`PyGetSetDef` structures. For Python implementations without such
594 types, this method will always return ``False``.
595
596
597 .. function:: ismemberdescriptor(object)
598
599 Return ``True`` if the object is a member descriptor.
600
601 .. impl-detail::
602
603 Member descriptors are attributes defined in extension modules via
604 :c:type:`PyMemberDef` structures. For Python implementations without such
605 types, this method will always return ``False``.
606
607
608 .. _inspect-source:
609
610 Retrieving source code
611 ----------------------
612
613 .. function:: getdoc(object)
614
615 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
616 If the documentation string for an object is not provided and the object is
617 a class, a method, a property or a descriptor, retrieve the documentation
618 string from the inheritance hierarchy.
619 Return ``None`` if the documentation string is invalid or missing.
620
621 .. versionchanged:: 3.5
622 Documentation strings are now inherited if not overridden.
623
624
625 .. function:: getcomments(object)
626
627 Return in a single string any lines of comments immediately preceding the
628 object's source code (for a class, function, or method), or at the top of the
629 Python source file (if the object is a module). If the object's source code
630 is unavailable, return ``None``. This could happen if the object has been
631 defined in C or the interactive shell.
632
633
634 .. function:: getfile(object)
635
636 Return the name of the (text or binary) file in which an object was defined.
637 This will fail with a :exc:`TypeError` if the object is a built-in module,
638 class, or function.
639
640
641 .. function:: getmodule(object)
642
643 Try to guess which module an object was defined in. Return ``None``
644 if the module cannot be determined.
645
646
647 .. function:: getsourcefile(object)
648
649 Return the name of the Python source file in which an object was defined
650 or ``None`` if no way can be identified to get the source. This
651 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
652 function.
653
654
655 .. function:: getsourcelines(object)
656
657 Return a list of source lines and starting line number for an object. The
658 argument may be a module, class, method, function, traceback, frame, or code
659 object. The source code is returned as a list of the lines corresponding to the
660 object and the line number indicates where in the original source file the first
661 line of code was found. An :exc:`OSError` is raised if the source code cannot
662 be retrieved.
663 A :exc:`TypeError` is raised if the object is a built-in module, class, or
664 function.
665
666 .. versionchanged:: 3.3
667 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
668 former.
669
670
671 .. function:: getsource(object)
672
673 Return the text of the source code for an object. The argument may be a module,
674 class, method, function, traceback, frame, or code object. The source code is
675 returned as a single string. An :exc:`OSError` is raised if the source code
676 cannot be retrieved.
677 A :exc:`TypeError` is raised if the object is a built-in module, class, or
678 function.
679
680 .. versionchanged:: 3.3
681 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
682 former.
683
684
685 .. function:: cleandoc(doc)
686
687 Clean up indentation from docstrings that are indented to line up with blocks
688 of code.
689
690 All leading whitespace is removed from the first line. Any leading whitespace
691 that can be uniformly removed from the second line onwards is removed. Empty
692 lines at the beginning and end are subsequently removed. Also, all tabs are
693 expanded to spaces.
694
695
696 .. _inspect-signature-object:
697
698 Introspecting callables with the Signature object
699 -------------------------------------------------
700
701 .. versionadded:: 3.3
702
703 The :class:`Signature` object represents the call signature of a callable object
704 and its return annotation. To retrieve a :class:`!Signature` object,
705 use the :func:`!signature`
706 function.
707
708 .. function:: signature(callable, *, follow_wrapped=True, globals=None, locals=None, eval_str=False)
709
710 Return a :class:`Signature` object for the given *callable*:
711
712 .. doctest::
713
714 >>> from inspect import signature
715 >>> def foo(a, *, b:int, **kwargs):
716 ... pass
717
718 >>> sig = signature(foo)
719
720 >>> str(sig)
721 '(a, *, b: int, **kwargs)'
722
723 >>> str(sig.parameters['b'])
724 'b: int'
725
726 >>> sig.parameters['b'].annotation
727 <class 'int'>
728
729 Accepts a wide range of Python callables, from plain functions and classes to
730 :func:`functools.partial` objects.
731
732 For objects defined in modules using stringized annotations
733 (``from __future__ import annotations``), :func:`signature` will
734 attempt to automatically un-stringize the annotations using
735 :func:`get_annotations`. The
736 *globals*, *locals*, and *eval_str* parameters are passed
737 into :func:`get_annotations` when resolving the
738 annotations; see the documentation for :func:`get_annotations`
739 for instructions on how to use these parameters.
740
741 Raises :exc:`ValueError` if no signature can be provided, and
742 :exc:`TypeError` if that type of object is not supported. Also,
743 if the annotations are stringized, and *eval_str* is not false,
744 the ``eval()`` call(s) to un-stringize the annotations in :func:`get_annotations`
745 could potentially raise any kind of exception.
746
747 A slash(/) in the signature of a function denotes that the parameters prior
748 to it are positional-only. For more info, see
749 :ref:`the FAQ entry on positional-only parameters <faq-positional-only-arguments>`.
750
751 .. versionchanged:: 3.5
752 The *follow_wrapped* parameter was added.
753 Pass ``False`` to get a signature of
754 *callable* specifically (``callable.__wrapped__`` will not be used to
755 unwrap decorated callables.)
756
757 .. versionchanged:: 3.10
758 The *globals*, *locals*, and *eval_str* parameters were added.
759
760 .. note::
761
762 Some callables may not be introspectable in certain implementations of
763 Python. For example, in CPython, some built-in functions defined in
764 C provide no metadata about their arguments.
765
766 .. impl-detail::
767
768 If the passed object has a :attr:`!__signature__` attribute,
769 we may use it to create the signature.
770 The exact semantics are an implementation detail and are subject to
771 unannounced changes. Consult the source code for current semantics.
772
773
774 .. class:: Signature(parameters=None, *, return_annotation=Signature.empty)
775
776 A :class:`!Signature` object represents the call signature of a function
777 and its return
778 annotation. For each parameter accepted by the function it stores a
779 :class:`Parameter` object in its :attr:`parameters` collection.
780
781 The optional *parameters* argument is a sequence of :class:`Parameter`
782 objects, which is validated to check that there are no parameters with
783 duplicate names, and that the parameters are in the right order, i.e.
784 positional-only first, then positional-or-keyword, and that parameters with
785 defaults follow parameters without defaults.
786
787 The optional *return_annotation* argument can be an arbitrary Python object.
788 It represents the "return" annotation of the callable.
789
790 :class:`!Signature` objects are *immutable*. Use :meth:`Signature.replace` or
791 :func:`copy.replace` to make a modified copy.
792
793 .. versionchanged:: 3.5
794 :class:`!Signature` objects are now picklable and :term:`hashable`.
795
796 .. attribute:: Signature.empty
797
798 A special class-level marker to specify absence of a return annotation.
799
800 .. attribute:: Signature.parameters
801
802 An ordered mapping of parameters' names to the corresponding
803 :class:`Parameter` objects. Parameters appear in strict definition
804 order, including keyword-only parameters.
805
806 .. versionchanged:: 3.7
807 Python only explicitly guaranteed that it preserved the declaration
808 order of keyword-only parameters as of version 3.7, although in practice
809 this order had always been preserved in Python 3.
810
811 .. attribute:: Signature.return_annotation
812
813 The "return" annotation for the callable. If the callable has no "return"
814 annotation, this attribute is set to :attr:`Signature.empty`.
815
816 .. method:: Signature.bind(*args, **kwargs)
817
818 Create a mapping from positional and keyword arguments to parameters.
819 Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
820 signature, or raises a :exc:`TypeError`.
821
822 .. method:: Signature.bind_partial(*args, **kwargs)
823
824 Works the same way as :meth:`Signature.bind`, but allows the omission of
825 some required arguments (mimics :func:`functools.partial` behavior.)
826 Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
827 passed arguments do not match the signature.
828
829 .. method:: Signature.replace(*[, parameters][, return_annotation])
830
831 Create a new :class:`Signature` instance based on the instance
832 :meth:`replace` was invoked on.
833 It is possible to pass different *parameters* and/or
834 *return_annotation* to override the corresponding properties of the base
835 signature. To remove ``return_annotation`` from the copied
836 :class:`!Signature`, pass in
837 :attr:`Signature.empty`.
838
839 .. doctest::
840
841 >>> def test(a, b):
842 ... pass
843 ...
844 >>> sig = signature(test)
845 >>> new_sig = sig.replace(return_annotation="new return anno")
846 >>> str(new_sig)
847 "(a, b) -> 'new return anno'"
848
849 :class:`Signature` objects are also supported by the generic function
850 :func:`copy.replace`.
851
852 .. method:: format(*, max_width=None)
853
854 Create a string representation of the :class:`Signature` object.
855
856 If *max_width* is passed, the method will attempt to fit
857 the signature into lines of at most *max_width* characters.
858 If the signature is longer than *max_width*,
859 all parameters will be on separate lines.
860
861 .. versionadded:: 3.13
862
863 .. classmethod:: Signature.from_callable(obj, *, follow_wrapped=True, globals=None, locals=None, eval_str=False)
864
865 Return a :class:`Signature` (or its subclass) object for a given callable
866 *obj*.
867
868 This method simplifies subclassing of :class:`Signature`:
869
870 .. testcode::
871
872 class MySignature(Signature):
873 pass
874 sig = MySignature.from_callable(sum)
875 assert isinstance(sig, MySignature)
876
877 Its behavior is otherwise identical to that of :func:`signature`.
878
879 .. versionadded:: 3.5
880
881 .. versionchanged:: 3.10
882 The *globals*, *locals*, and *eval_str* parameters were added.
883
884
885 .. class:: Parameter(name, kind, *, default=Parameter.empty, annotation=Parameter.empty)
886
887 :class:`!Parameter` objects are *immutable*.
888 Instead of modifying a :class:`!Parameter` object,
889 you can use :meth:`Parameter.replace` or :func:`copy.replace` to create a modified copy.
890
891 .. versionchanged:: 3.5
892 Parameter objects are now picklable and :term:`hashable`.
893
894 .. attribute:: Parameter.empty
895
896 A special class-level marker to specify absence of default values and
897 annotations.
898
899 .. attribute:: Parameter.name
900
901 The name of the parameter as a string. The name must be a valid
902 Python identifier.
903
904 .. impl-detail::
905
906 CPython generates implicit parameter names of the form ``.0`` on the
907 code objects used to implement comprehensions and generator
908 expressions.
909
910 .. versionchanged:: 3.6
911 These parameter names are now exposed by this module as names like
912 ``implicit0``.
913
914 .. attribute:: Parameter.default
915
916 The default value for the parameter. If the parameter has no default
917 value, this attribute is set to :attr:`Parameter.empty`.
918
919 .. attribute:: Parameter.annotation
920
921 The annotation for the parameter. If the parameter has no annotation,
922 this attribute is set to :attr:`Parameter.empty`.
923
924 .. attribute:: Parameter.kind
925
926 Describes how argument values are bound to the parameter. The possible
927 values are accessible via :class:`Parameter` (like ``Parameter.KEYWORD_ONLY``),
928 and support comparison and ordering, in the following order:
929
930 .. tabularcolumns:: |l|L|
931
932 +------------------------+----------------------------------------------+
933 | Name | Meaning |
934 +========================+==============================================+
935 | *POSITIONAL_ONLY* | Value must be supplied as a positional |
936 | | argument. Positional only parameters are |
937 | | those which appear before a ``/`` entry (if |
938 | | present) in a Python function definition. |
939 +------------------------+----------------------------------------------+
940 | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
941 | | positional argument (this is the standard |
942 | | binding behaviour for functions implemented |
943 | | in Python.) |
944 +------------------------+----------------------------------------------+
945 | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
946 | | bound to any other parameter. This |
947 | | corresponds to a ``*args`` parameter in a |
948 | | Python function definition. |
949 +------------------------+----------------------------------------------+
950 | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
951 | | Keyword only parameters are those which |
952 | | appear after a ``*`` or ``*args`` entry in a |
953 | | Python function definition. |
954 +------------------------+----------------------------------------------+
955 | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
956 | | to any other parameter. This corresponds to a|
957 | | ``**kwargs`` parameter in a Python function |
958 | | definition. |
959 +------------------------+----------------------------------------------+
960
961 Example: print all keyword-only arguments without default values:
962
963 .. doctest::
964
965 >>> def foo(a, b, *, c, d=10):
966 ... pass
967
968 >>> sig = signature(foo)
969 >>> for param in sig.parameters.values():
970 ... if (param.kind == param.KEYWORD_ONLY and
971 ... param.default is param.empty):
972 ... print('Parameter:', param)
973 Parameter: c
974
975 .. attribute:: Parameter.kind.description
976
977 Describes an enum value of :attr:`Parameter.kind`.
978
979 .. versionadded:: 3.8
980
981 Example: print all descriptions of arguments:
982
983 .. doctest::
984
985 >>> def foo(a, b, *, c, d=10):
986 ... pass
987
988 >>> sig = signature(foo)
989 >>> for param in sig.parameters.values():
990 ... print(param.kind.description)
991 positional or keyword
992 positional or keyword
993 keyword-only
994 keyword-only
995
996 .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
997
998 Create a new :class:`Parameter` instance based on the instance replaced was invoked
999 on. To override a :class:`!Parameter` attribute, pass the corresponding
1000 argument. To remove a default value or/and an annotation from a
1001 :class:`!Parameter`, pass :attr:`Parameter.empty`.
1002
1003 .. doctest::
1004
1005 >>> from inspect import Parameter
1006 >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
1007 >>> str(param)
1008 'foo=42'
1009
1010 >>> str(param.replace()) # Will create a shallow copy of 'param'
1011 'foo=42'
1012
1013 >>> str(param.replace(default=Parameter.empty, annotation='spam'))
1014 "foo: 'spam'"
1015
1016 :class:`Parameter` objects are also supported by the generic function
1017 :func:`copy.replace`.
1018
1019 .. versionchanged:: 3.4
1020 In Python 3.3 :class:`Parameter` objects were allowed to have ``name`` set
1021 to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``.
1022 This is no longer permitted.
1023
1024 .. class:: BoundArguments
1025
1026 Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
1027 Holds the mapping of arguments to the function's parameters.
1028
1029 .. attribute:: BoundArguments.arguments
1030
1031 A mutable mapping of parameters' names to arguments' values.
1032 Contains only explicitly bound arguments. Changes in :attr:`arguments`
1033 will reflect in :attr:`args` and :attr:`kwargs`.
1034
1035 Should be used in conjunction with :attr:`Signature.parameters` for any
1036 argument processing purposes.
1037
1038 .. note::
1039
1040 Arguments for which :meth:`Signature.bind` or
1041 :meth:`Signature.bind_partial` relied on a default value are skipped.
1042 However, if needed, use :meth:`BoundArguments.apply_defaults` to add
1043 them.
1044
1045 .. versionchanged:: 3.9
1046 :attr:`arguments` is now of type :class:`dict`. Formerly, it was of
1047 type :class:`collections.OrderedDict`.
1048
1049 .. attribute:: BoundArguments.args
1050
1051 A tuple of positional arguments values. Dynamically computed from the
1052 :attr:`arguments` attribute.
1053
1054 .. attribute:: BoundArguments.kwargs
1055
1056 A dict of keyword arguments values. Dynamically computed from the
1057 :attr:`arguments` attribute. Arguments that can be passed positionally
1058 are included in :attr:`args` instead.
1059
1060 .. attribute:: BoundArguments.signature
1061
1062 A reference to the parent :class:`Signature` object.
1063
1064 .. method:: BoundArguments.apply_defaults()
1065
1066 Set default values for missing arguments.
1067
1068 For variable-positional arguments (``*args``) the default is an
1069 empty tuple.
1070
1071 For variable-keyword arguments (``**kwargs``) the default is an
1072 empty dict.
1073
1074 .. doctest::
1075
1076 >>> def foo(a, b='ham', *args): pass
1077 >>> ba = inspect.signature(foo).bind('spam')
1078 >>> ba.apply_defaults()
1079 >>> ba.arguments
1080 {'a': 'spam', 'b': 'ham', 'args': ()}
1081
1082 .. versionadded:: 3.5
1083
1084 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
1085 functions:
1086
1087 .. testcode::
1088
1089 def test(a, *, b):
1090 ...
1091
1092 sig = signature(test)
1093 ba = sig.bind(10, b=20)
1094 test(*ba.args, **ba.kwargs)
1095
1096
1097 .. seealso::
1098
1099 :pep:`362` - Function Signature Object.
1100 The detailed specification, implementation details and examples.
1101
1102
1103 .. _inspect-classes-functions:
1104
1105 Classes and functions
1106 ---------------------
1107
1108 .. function:: getclasstree(classes, unique=False)
1109
1110 Arrange the given list of classes into a hierarchy of nested lists. Where a
1111 nested list appears, it contains classes derived from the class whose entry
1112 immediately precedes the list. Each entry is a 2-tuple containing a class and a
1113 tuple of its base classes. If the *unique* argument is true, exactly one entry
1114 appears in the returned structure for each class in the given list. Otherwise,
1115 classes using multiple inheritance and their descendants will appear multiple
1116 times.
1117
1118
1119 .. function:: getfullargspec(func)
1120
1121 Get the names and default values of a Python function's parameters. A
1122 :term:`named tuple` is returned:
1123
1124 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
1125 annotations)``
1126
1127 *args* is a list of the positional parameter names.
1128 *varargs* is the name of the ``*`` parameter or ``None`` if arbitrary
1129 positional arguments are not accepted.
1130 *varkw* is the name of the ``**`` parameter or ``None`` if arbitrary
1131 keyword arguments are not accepted.
1132 *defaults* is an *n*-tuple of default argument values corresponding to the
1133 last *n* positional parameters, or ``None`` if there are no such defaults
1134 defined.
1135 *kwonlyargs* is a list of keyword-only parameter names in declaration order.
1136 *kwonlydefaults* is a dictionary mapping parameter names from *kwonlyargs*
1137 to the default values used if no argument is supplied.
1138 *annotations* is a dictionary mapping parameter names to annotations.
1139 The special key ``"return"`` is used to report the function return value
1140 annotation (if any).
1141
1142 Note that :func:`signature` and
1143 :ref:`Signature Object <inspect-signature-object>` provide the recommended
1144 API for callable introspection, and support additional behaviours (like
1145 positional-only arguments) that are sometimes encountered in extension module
1146 APIs. This function is retained primarily for use in code that needs to
1147 maintain compatibility with the Python 2 ``inspect`` module API.
1148
1149 .. versionchanged:: 3.4
1150 This function is now based on :func:`signature`, but still ignores
1151 ``__wrapped__`` attributes and includes the already bound first
1152 parameter in the signature output for bound methods.
1153
1154 .. versionchanged:: 3.6
1155 This method was previously documented as deprecated in favour of
1156 :func:`signature` in Python 3.5, but that decision has been reversed
1157 in order to restore a clearly supported standard interface for
1158 single-source Python 2/3 code migrating away from the legacy
1159 :func:`!getargspec` API.
1160
1161 .. versionchanged:: 3.7
1162 Python only explicitly guaranteed that it preserved the declaration
1163 order of keyword-only parameters as of version 3.7, although in practice
1164 this order had always been preserved in Python 3.
1165
1166
1167 .. function:: getargvalues(frame)
1168
1169 Get information about arguments passed into a particular frame. A
1170 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
1171 returned. *args* is a list of the argument names. *varargs* and *keywords*
1172 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
1173 locals dictionary of the given frame.
1174
1175 .. note::
1176 This function was inadvertently marked as deprecated in Python 3.5.
1177
1178
1179 .. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
1180
1181 Format a pretty argument spec from the four values returned by
1182 :func:`getargvalues`. The format\* arguments are the corresponding optional
1183 formatting functions that are called to turn names and values into strings.
1184
1185 .. note::
1186 This function was inadvertently marked as deprecated in Python 3.5.
1187
1188
1189 .. function:: getmro(cls)
1190
1191 Return a tuple of class cls's base classes, including cls, in method resolution
1192 order. No class appears more than once in this tuple. Note that the method
1193 resolution order depends on cls's type. Unless a very peculiar user-defined
1194 metatype is in use, cls will be the first element of the tuple.
1195
1196
1197 .. function:: getcallargs(func, /, *args, **kwds)
1198
1199 Bind the *args* and *kwds* to the argument names of the Python function or
1200 method *func*, as if it was called with them. For bound methods, bind also the
1201 first argument (typically named ``self``) to the associated instance. A dict
1202 is returned, mapping the argument names (including the names of the ``*`` and
1203 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
1204 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
1205 an exception because of incompatible signature, an exception of the same type
1206 and the same or similar message is raised. For example:
1207
1208 .. doctest::
1209
1210 >>> from inspect import getcallargs
1211 >>> def f(a, b=1, *pos, **named):
1212 ... pass
1213 ...
1214 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
1215 True
1216 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
1217 True
1218 >>> getcallargs(f)
1219 Traceback (most recent call last):
1220 ...
1221 TypeError: f() missing 1 required positional argument: 'a'
1222
1223 .. versionadded:: 3.2
1224
1225 .. deprecated:: 3.5
1226 Use :meth:`Signature.bind` and :meth:`Signature.bind_partial` instead.
1227
1228
1229 .. function:: getclosurevars(func)
1230
1231 Get the mapping of external name references in a Python function or
1232 method *func* to their current values. A
1233 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
1234 is returned. *nonlocals* maps referenced names to lexical closure
1235 variables, *globals* to the function's module globals and *builtins* to
1236 the builtins visible from the function body. *unbound* is the set of names
1237 referenced in the function that could not be resolved at all given the
1238 current module globals and builtins.
1239
1240 :exc:`TypeError` is raised if *func* is not a Python function or method.
1241
1242 .. versionadded:: 3.3
1243
1244
1245 .. function:: unwrap(func, *, stop=None)
1246
1247 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
1248 attributes returning the last object in the chain.
1249
1250 *stop* is an optional callback accepting an object in the wrapper chain
1251 as its sole argument that allows the unwrapping to be terminated early if
1252 the callback returns a true value. If the callback never returns a true
1253 value, the last object in the chain is returned as usual. For example,
1254 :func:`signature` uses this to stop unwrapping if any object in the
1255 chain has a ``__signature__`` attribute defined.
1256
1257 :exc:`ValueError` is raised if a cycle is encountered.
1258
1259 .. versionadded:: 3.4
1260
1261
1262 .. function:: get_annotations(obj, *, globals=None, locals=None, eval_str=False)
1263
1264 Compute the annotations dict for an object.
1265
1266 ``obj`` may be a callable, class, or module.
1267 Passing in an object of any other type raises :exc:`TypeError`.
1268
1269 Returns a dict. ``get_annotations()`` returns a new dict every time
1270 it's called; calling it twice on the same object will return two
1271 different but equivalent dicts.
1272
1273 This function handles several details for you:
1274
1275 * If ``eval_str`` is true, values of type ``str`` will
1276 be un-stringized using :func:`eval`. This is intended
1277 for use with stringized annotations
1278 (``from __future__ import annotations``).
1279 * If ``obj`` doesn't have an annotations dict, returns an
1280 empty dict. (Functions and methods always have an
1281 annotations dict; classes, modules, and other types of
1282 callables may not.)
1283 * Ignores inherited annotations on classes. If a class
1284 doesn't have its own annotations dict, returns an empty dict.
1285 * All accesses to object members and dict values are done
1286 using ``getattr()`` and ``dict.get()`` for safety.
1287 * Always, always, always returns a freshly created dict.
1288
1289 ``eval_str`` controls whether or not values of type ``str`` are replaced
1290 with the result of calling :func:`eval` on those values:
1291
1292 * If eval_str is true, :func:`eval` is called on values of type ``str``.
1293 (Note that ``get_annotations`` doesn't catch exceptions; if :func:`eval`
1294 raises an exception, it will unwind the stack past the ``get_annotations``
1295 call.)
1296 * If eval_str is false (the default), values of type ``str`` are unchanged.
1297
1298 ``globals`` and ``locals`` are passed in to :func:`eval`; see the documentation
1299 for :func:`eval` for more information. If ``globals`` or ``locals``
1300 is ``None``, this function may replace that value with a context-specific
1301 default, contingent on ``type(obj)``:
1302
1303 * If ``obj`` is a module, ``globals`` defaults to ``obj.__dict__``.
1304 * If ``obj`` is a class, ``globals`` defaults to
1305 ``sys.modules[obj.__module__].__dict__`` and ``locals`` defaults
1306 to the ``obj`` class namespace.
1307 * If ``obj`` is a callable, ``globals`` defaults to
1308 :attr:`obj.__globals__ <function.__globals__>`,
1309 although if ``obj`` is a wrapped function (using
1310 :func:`functools.update_wrapper`) it is first unwrapped.
1311
1312 Calling ``get_annotations`` is best practice for accessing the
1313 annotations dict of any object. See :ref:`annotations-howto` for
1314 more information on annotations best practices.
1315
1316 .. versionadded:: 3.10
1317
1318
1319 .. _inspect-stack:
1320
1321 The interpreter stack
1322 ---------------------
1323
1324 Some of the following functions return
1325 :class:`FrameInfo` objects. For backwards compatibility these objects allow
1326 tuple-like operations on all attributes except ``positions``. This behavior
1327 is considered deprecated and may be removed in the future.
1328
1329 .. class:: FrameInfo
1330
1331 .. attribute:: frame
1332
1333 The :ref:`frame object <frame-objects>` that the record corresponds to.
1334
1335 .. attribute:: filename
1336
1337 The file name associated with the code being executed by the frame this record
1338 corresponds to.
1339
1340 .. attribute:: lineno
1341
1342 The line number of the current line associated with the code being
1343 executed by the frame this record corresponds to.
1344
1345 .. attribute:: function
1346
1347 The function name that is being executed by the frame this record corresponds to.
1348
1349 .. attribute:: code_context
1350
1351 A list of lines of context from the source code that's being executed by the frame
1352 this record corresponds to.
1353
1354 .. attribute:: index
1355
1356 The index of the current line being executed in the :attr:`code_context` list.
1357
1358 .. attribute:: positions
1359
1360 A :class:`dis.Positions` object containing the start line number, end line
1361 number, start column offset, and end column offset associated with the
1362 instruction being executed by the frame this record corresponds to.
1363
1364 .. versionchanged:: 3.5
1365 Return a :term:`named tuple` instead of a :class:`tuple`.
1366
1367 .. versionchanged:: 3.11
1368 :class:`!FrameInfo` is now a class instance
1369 (that is backwards compatible with the previous :term:`named tuple`).
1370
1371
1372 .. class:: Traceback
1373
1374 .. attribute:: filename
1375
1376 The file name associated with the code being executed by the frame this traceback
1377 corresponds to.
1378
1379 .. attribute:: lineno
1380
1381 The line number of the current line associated with the code being
1382 executed by the frame this traceback corresponds to.
1383
1384 .. attribute:: function
1385
1386 The function name that is being executed by the frame this traceback corresponds to.
1387
1388 .. attribute:: code_context
1389
1390 A list of lines of context from the source code that's being executed by the frame
1391 this traceback corresponds to.
1392
1393 .. attribute:: index
1394
1395 The index of the current line being executed in the :attr:`code_context` list.
1396
1397 .. attribute:: positions
1398
1399 A :class:`dis.Positions` object containing the start line number, end
1400 line number, start column offset, and end column offset associated with
1401 the instruction being executed by the frame this traceback corresponds
1402 to.
1403
1404 .. versionchanged:: 3.11
1405 :class:`!Traceback` is now a class instance
1406 (that is backwards compatible with the previous :term:`named tuple`).
1407
1408
1409 .. note::
1410
1411 Keeping references to frame objects, as found in the first element of the frame
1412 records these functions return, can cause your program to create reference
1413 cycles. Once a reference cycle has been created, the lifespan of all objects
1414 which can be accessed from the objects which form the cycle can become much
1415 longer even if Python's optional cycle detector is enabled. If such cycles must
1416 be created, it is important to ensure they are explicitly broken to avoid the
1417 delayed destruction of objects and increased memory consumption which occurs.
1418
1419 Though the cycle detector will catch these, destruction of the frames (and local
1420 variables) can be made deterministic by removing the cycle in a
1421 :keyword:`finally` clause. This is also important if the cycle detector was
1422 disabled when Python was compiled or using :func:`gc.disable`. For example::
1423
1424 def handle_stackframe_without_leak():
1425 frame = inspect.currentframe()
1426 try:
1427 # do something with the frame
1428 finally:
1429 del frame
1430
1431 If you want to keep the frame around (for example to print a traceback
1432 later), you can also break reference cycles by using the
1433 :meth:`frame.clear` method.
1434
1435 The optional *context* argument supported by most of these functions specifies
1436 the number of lines of context to return, which are centered around the current
1437 line.
1438
1439
1440 .. function:: getframeinfo(frame, context=1)
1441
1442 Get information about a frame or traceback object. A :class:`Traceback` object
1443 is returned.
1444
1445 .. versionchanged:: 3.11
1446 A :class:`Traceback` object is returned instead of a named tuple.
1447
1448 .. function:: getouterframes(frame, context=1)
1449
1450 Get a list of :class:`FrameInfo` objects for a frame and all outer frames.
1451 These frames represent the calls that lead to the creation of *frame*. The
1452 first entry in the returned list represents *frame*; the last entry
1453 represents the outermost call on *frame*'s stack.
1454
1455 .. versionchanged:: 3.5
1456 A list of :term:`named tuples <named tuple>`
1457 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1458 is returned.
1459
1460 .. versionchanged:: 3.11
1461 A list of :class:`FrameInfo` objects is returned.
1462
1463 .. function:: getinnerframes(traceback, context=1)
1464
1465 Get a list of :class:`FrameInfo` objects for a traceback's frame and all
1466 inner frames. These frames represent calls made as a consequence of *frame*.
1467 The first entry in the list represents *traceback*; the last entry represents
1468 where the exception was raised.
1469
1470 .. versionchanged:: 3.5
1471 A list of :term:`named tuples <named tuple>`
1472 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1473 is returned.
1474
1475 .. versionchanged:: 3.11
1476 A list of :class:`FrameInfo` objects is returned.
1477
1478 .. function:: currentframe()
1479
1480 Return the frame object for the caller's stack frame.
1481
1482 .. impl-detail::
1483
1484 This function relies on Python stack frame support in the interpreter,
1485 which isn't guaranteed to exist in all implementations of Python. If
1486 running in an implementation without Python stack frame support this
1487 function returns ``None``.
1488
1489
1490 .. function:: stack(context=1)
1491
1492 Return a list of :class:`FrameInfo` objects for the caller's stack. The
1493 first entry in the returned list represents the caller; the last entry
1494 represents the outermost call on the stack.
1495
1496 .. versionchanged:: 3.5
1497 A list of :term:`named tuples <named tuple>`
1498 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1499 is returned.
1500
1501 .. versionchanged:: 3.11
1502 A list of :class:`FrameInfo` objects is returned.
1503
1504 .. function:: trace(context=1)
1505
1506 Return a list of :class:`FrameInfo` objects for the stack between the current
1507 frame and the frame in which an exception currently being handled was raised
1508 in. The first entry in the list represents the caller; the last entry
1509 represents where the exception was raised.
1510
1511 .. versionchanged:: 3.5
1512 A list of :term:`named tuples <named tuple>`
1513 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1514 is returned.
1515
1516 .. versionchanged:: 3.11
1517 A list of :class:`FrameInfo` objects is returned.
1518
1519 Fetching attributes statically
1520 ------------------------------
1521
1522 Both :func:`getattr` and :func:`hasattr` can trigger code execution when
1523 fetching or checking for the existence of attributes. Descriptors, like
1524 properties, will be invoked and :meth:`~object.__getattr__` and
1525 :meth:`~object.__getattribute__`
1526 may be called.
1527
1528 For cases where you want passive introspection, like documentation tools, this
1529 can be inconvenient. :func:`getattr_static` has a similar signature as :func:`getattr`
1530 but avoids executing code when it fetches attributes.
1531
1532 .. function:: getattr_static(obj, attr)
1533 getattr_static(obj, attr, default)
1534
1535 Retrieve attributes without triggering dynamic lookup via the
1536 descriptor protocol, :meth:`~object.__getattr__`
1537 or :meth:`~object.__getattribute__`.
1538
1539 Note: this function may not be able to retrieve all attributes
1540 that getattr can fetch (like dynamically created attributes)
1541 and may find attributes that getattr can't (like descriptors
1542 that raise AttributeError). It can also return descriptors objects
1543 instead of instance members.
1544
1545 If the instance :attr:`~object.__dict__` is shadowed by another member (for
1546 example a property) then this function will be unable to find instance
1547 members.
1548
1549 .. versionadded:: 3.2
1550
1551 :func:`getattr_static` does not resolve descriptors, for example slot descriptors or
1552 getset descriptors on objects implemented in C. The descriptor object
1553 is returned instead of the underlying attribute.
1554
1555 You can handle these with code like the following. Note that
1556 for arbitrary getset descriptors invoking these may trigger
1557 code execution::
1558
1559 # example code for resolving the builtin descriptor types
1560 class _foo:
1561 __slots__ = ['foo']
1562
1563 slot_descriptor = type(_foo.foo)
1564 getset_descriptor = type(type(open(__file__)).name)
1565 wrapper_descriptor = type(str.__dict__['__add__'])
1566 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
1567
1568 result = getattr_static(some_object, 'foo')
1569 if type(result) in descriptor_types:
1570 try:
1571 result = result.__get__()
1572 except AttributeError:
1573 # descriptors can raise AttributeError to
1574 # indicate there is no underlying value
1575 # in which case the descriptor itself will
1576 # have to do
1577 pass
1578
1579
1580 Current State of Generators, Coroutines, and Asynchronous Generators
1581 --------------------------------------------------------------------
1582
1583 When implementing coroutine schedulers and for other advanced uses of
1584 generators, it is useful to determine whether a generator is currently
1585 executing, is waiting to start or resume or execution, or has already
1586 terminated. :func:`getgeneratorstate` allows the current state of a
1587 generator to be determined easily.
1588
1589 .. function:: getgeneratorstate(generator)
1590
1591 Get current state of a generator-iterator.
1592
1593 Possible states are:
1594
1595 * GEN_CREATED: Waiting to start execution.
1596 * GEN_RUNNING: Currently being executed by the interpreter.
1597 * GEN_SUSPENDED: Currently suspended at a yield expression.
1598 * GEN_CLOSED: Execution has completed.
1599
1600 .. versionadded:: 3.2
1601
1602 .. function:: getcoroutinestate(coroutine)
1603
1604 Get current state of a coroutine object. The function is intended to be
1605 used with coroutine objects created by :keyword:`async def` functions, but
1606 will accept any coroutine-like object that has ``cr_running`` and
1607 ``cr_frame`` attributes.
1608
1609 Possible states are:
1610
1611 * CORO_CREATED: Waiting to start execution.
1612 * CORO_RUNNING: Currently being executed by the interpreter.
1613 * CORO_SUSPENDED: Currently suspended at an await expression.
1614 * CORO_CLOSED: Execution has completed.
1615
1616 .. versionadded:: 3.5
1617
1618 .. function:: getasyncgenstate(agen)
1619
1620 Get current state of an asynchronous generator object. The function is
1621 intended to be used with asynchronous iterator objects created by
1622 :keyword:`async def` functions which use the :keyword:`yield` statement,
1623 but will accept any asynchronous generator-like object that has
1624 ``ag_running`` and ``ag_frame`` attributes.
1625
1626 Possible states are:
1627
1628 * AGEN_CREATED: Waiting to start execution.
1629 * AGEN_RUNNING: Currently being executed by the interpreter.
1630 * AGEN_SUSPENDED: Currently suspended at a yield expression.
1631 * AGEN_CLOSED: Execution has completed.
1632
1633 .. versionadded:: 3.12
1634
1635 The current internal state of the generator can also be queried. This is
1636 mostly useful for testing purposes, to ensure that internal state is being
1637 updated as expected:
1638
1639 .. function:: getgeneratorlocals(generator)
1640
1641 Get the mapping of live local variables in *generator* to their current
1642 values. A dictionary is returned that maps from variable names to values.
1643 This is the equivalent of calling :func:`locals` in the body of the
1644 generator, and all the same caveats apply.
1645
1646 If *generator* is a :term:`generator` with no currently associated frame,
1647 then an empty dictionary is returned. :exc:`TypeError` is raised if
1648 *generator* is not a Python generator object.
1649
1650 .. impl-detail::
1651
1652 This function relies on the generator exposing a Python stack frame
1653 for introspection, which isn't guaranteed to be the case in all
1654 implementations of Python. In such cases, this function will always
1655 return an empty dictionary.
1656
1657 .. versionadded:: 3.3
1658
1659 .. function:: getcoroutinelocals(coroutine)
1660
1661 This function is analogous to :func:`~inspect.getgeneratorlocals`, but
1662 works for coroutine objects created by :keyword:`async def` functions.
1663
1664 .. versionadded:: 3.5
1665
1666 .. function:: getasyncgenlocals(agen)
1667
1668 This function is analogous to :func:`~inspect.getgeneratorlocals`, but
1669 works for asynchronous generator objects created by :keyword:`async def`
1670 functions which use the :keyword:`yield` statement.
1671
1672 .. versionadded:: 3.12
1673
1674
1675 .. _inspect-module-co-flags:
1676
1677 Code Objects Bit Flags
1678 ----------------------
1679
1680 Python code objects have a :attr:`~codeobject.co_flags` attribute,
1681 which is a bitmap of the following flags:
1682
1683 .. data:: CO_OPTIMIZED
1684
1685 The code object is optimized, using fast locals.
1686
1687 .. data:: CO_NEWLOCALS
1688
1689 If set, a new dict will be created for the frame's :attr:`~frame.f_locals`
1690 when the code object is executed.
1691
1692 .. data:: CO_VARARGS
1693
1694 The code object has a variable positional parameter (``*args``-like).
1695
1696 .. data:: CO_VARKEYWORDS
1697
1698 The code object has a variable keyword parameter (``**kwargs``-like).
1699
1700 .. data:: CO_NESTED
1701
1702 The flag is set when the code object is a nested function.
1703
1704 .. data:: CO_GENERATOR
1705
1706 The flag is set when the code object is a generator function, i.e.
1707 a generator object is returned when the code object is executed.
1708
1709 .. data:: CO_COROUTINE
1710
1711 The flag is set when the code object is a coroutine function.
1712 When the code object is executed it returns a coroutine object.
1713 See :pep:`492` for more details.
1714
1715 .. versionadded:: 3.5
1716
1717 .. data:: CO_ITERABLE_COROUTINE
1718
1719 The flag is used to transform generators into generator-based
1720 coroutines. Generator objects with this flag can be used in
1721 ``await`` expression, and can ``yield from`` coroutine objects.
1722 See :pep:`492` for more details.
1723
1724 .. versionadded:: 3.5
1725
1726 .. data:: CO_ASYNC_GENERATOR
1727
1728 The flag is set when the code object is an asynchronous generator
1729 function. When the code object is executed it returns an
1730 asynchronous generator object. See :pep:`525` for more details.
1731
1732 .. versionadded:: 3.6
1733
1734 .. note::
1735 The flags are specific to CPython, and may not be defined in other
1736 Python implementations. Furthermore, the flags are an implementation
1737 detail, and can be removed or deprecated in future Python releases.
1738 It's recommended to use public APIs from the :mod:`inspect` module
1739 for any introspection needs.
1740
1741
1742 Buffer flags
1743 ------------
1744
1745 .. class:: BufferFlags
1746
1747 This is an :class:`enum.IntFlag` that represents the flags that
1748 can be passed to the :meth:`~object.__buffer__` method of objects
1749 implementing the :ref:`buffer protocol <bufferobjects>`.
1750
1751 The meaning of the flags is explained at :ref:`buffer-request-types`.
1752
1753 .. attribute:: BufferFlags.SIMPLE
1754 .. attribute:: BufferFlags.WRITABLE
1755 .. attribute:: BufferFlags.FORMAT
1756 .. attribute:: BufferFlags.ND
1757 .. attribute:: BufferFlags.STRIDES
1758 .. attribute:: BufferFlags.C_CONTIGUOUS
1759 .. attribute:: BufferFlags.F_CONTIGUOUS
1760 .. attribute:: BufferFlags.ANY_CONTIGUOUS
1761 .. attribute:: BufferFlags.INDIRECT
1762 .. attribute:: BufferFlags.CONTIG
1763 .. attribute:: BufferFlags.CONTIG_RO
1764 .. attribute:: BufferFlags.STRIDED
1765 .. attribute:: BufferFlags.STRIDED_RO
1766 .. attribute:: BufferFlags.RECORDS
1767 .. attribute:: BufferFlags.RECORDS_RO
1768 .. attribute:: BufferFlags.FULL
1769 .. attribute:: BufferFlags.FULL_RO
1770 .. attribute:: BufferFlags.READ
1771 .. attribute:: BufferFlags.WRITE
1772
1773 .. versionadded:: 3.12
1774
1775 .. _inspect-module-cli:
1776
1777 Command-line interface
1778 ----------------------
1779
1780 The :mod:`inspect` module also provides a basic introspection capability
1781 from the command line.
1782
1783 .. program:: inspect
1784
1785 By default, accepts the name of a module and prints the source of that
1786 module. A class or function within the module can be printed instead by
1787 appended a colon and the qualified name of the target object.
1788
1789 .. option:: --details
1790
1791 Print information about the specified object rather than the source code