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