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