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