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