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