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