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