1 :mod:`inspect` --- Inspect live objects 2 ======================================= 3 4 .. module:: inspect 5 :synopsis: Extract information and source code from live objects. 6 .. moduleauthor:: Ka-Ping Yee <ping (a] lfw.org> 7 .. sectionauthor:: Ka-Ping Yee <ping (a] lfw.org> 8 9 10 .. versionadded:: 2.1 11 12 **Source code:** :source:`Lib/inspect.py` 13 14 -------------- 15 16 The :mod:`inspect` module provides several useful functions to help get 17 information about live objects such as modules, classes, methods, functions, 18 tracebacks, frame objects, and code objects. For example, it can help you 19 examine the contents of a class, retrieve the source code of a method, extract 20 and format the argument list for a function, or get all the information you need 21 to display a detailed traceback. 22 23 There are four main kinds of services provided by this module: type checking, 24 getting source code, inspecting classes and functions, and examining the 25 interpreter stack. 26 27 28 .. _inspect-types: 29 30 Types and members 31 ----------------- 32 33 The :func:`getmembers` function retrieves the members of an object such as a 34 class or module. The sixteen functions whose names begin with "is" are mainly 35 provided as convenient choices for the second argument to :func:`getmembers`. 36 They also help you determine when you can expect to find the following special 37 attributes: 38 39 +-----------+-----------------+---------------------------+-------+ 40 | Type | Attribute | Description | Notes | 41 +===========+=================+===========================+=======+ 42 | module | __doc__ | documentation string | | 43 +-----------+-----------------+---------------------------+-------+ 44 | | __file__ | filename (missing for | | 45 | | | built-in modules) | | 46 +-----------+-----------------+---------------------------+-------+ 47 | class | __doc__ | documentation string | | 48 +-----------+-----------------+---------------------------+-------+ 49 | | __module__ | name of module in which | | 50 | | | this class was defined | | 51 +-----------+-----------------+---------------------------+-------+ 52 | method | __doc__ | documentation string | | 53 +-----------+-----------------+---------------------------+-------+ 54 | | __name__ | name with which this | | 55 | | | method was defined | | 56 +-----------+-----------------+---------------------------+-------+ 57 | | im_class | class object that asked | \(1) | 58 | | | for this method | | 59 +-----------+-----------------+---------------------------+-------+ 60 | | im_func or | function object | | 61 | | __func__ | containing implementation | | 62 | | | of method | | 63 +-----------+-----------------+---------------------------+-------+ 64 | | im_self or | instance to which this | | 65 | | __self__ | method is bound, or | | 66 | | | ``None`` | | 67 +-----------+-----------------+---------------------------+-------+ 68 | function | __doc__ | documentation string | | 69 +-----------+-----------------+---------------------------+-------+ 70 | | __name__ | name with which this | | 71 | | | function was defined | | 72 +-----------+-----------------+---------------------------+-------+ 73 | | func_code | code object containing | | 74 | | | compiled function | | 75 | | | :term:`bytecode` | | 76 +-----------+-----------------+---------------------------+-------+ 77 | | func_defaults | tuple of any default | | 78 | | | values for arguments | | 79 +-----------+-----------------+---------------------------+-------+ 80 | | func_doc | (same as __doc__) | | 81 +-----------+-----------------+---------------------------+-------+ 82 | | func_globals | global namespace in which | | 83 | | | this function was defined | | 84 +-----------+-----------------+---------------------------+-------+ 85 | | func_name | (same as __name__) | | 86 +-----------+-----------------+---------------------------+-------+ 87 | generator | __iter__ | defined to support | | 88 | | | iteration over container | | 89 +-----------+-----------------+---------------------------+-------+ 90 | | close | raises new GeneratorExit | | 91 | | | exception inside the | | 92 | | | generator to terminate | | 93 | | | the iteration | | 94 +-----------+-----------------+---------------------------+-------+ 95 | | gi_code | code object | | 96 +-----------+-----------------+---------------------------+-------+ 97 | | gi_frame | frame object or possibly | | 98 | | | ``None`` once the | | 99 | | | generator has been | | 100 | | | exhausted | | 101 +-----------+-----------------+---------------------------+-------+ 102 | | gi_running | set to 1 when generator | | 103 | | | is executing, 0 otherwise | | 104 +-----------+-----------------+---------------------------+-------+ 105 | | next | return the next item from | | 106 | | | the container | | 107 +-----------+-----------------+---------------------------+-------+ 108 | | send | resumes the generator and | | 109 | | | "sends" a value that | | 110 | | | becomes the result of the | | 111 | | | current yield-expression | | 112 +-----------+-----------------+---------------------------+-------+ 113 | | throw | used to raise an | | 114 | | | exception inside the | | 115 | | | generator | | 116 +-----------+-----------------+---------------------------+-------+ 117 | traceback | tb_frame | frame object at this | | 118 | | | level | | 119 +-----------+-----------------+---------------------------+-------+ 120 | | tb_lasti | index of last attempted | | 121 | | | instruction in bytecode | | 122 +-----------+-----------------+---------------------------+-------+ 123 | | tb_lineno | current line number in | | 124 | | | Python source code | | 125 +-----------+-----------------+---------------------------+-------+ 126 | | tb_next | next inner traceback | | 127 | | | object (called by this | | 128 | | | level) | | 129 +-----------+-----------------+---------------------------+-------+ 130 | frame | f_back | next outer frame object | | 131 | | | (this frame's caller) | | 132 +-----------+-----------------+---------------------------+-------+ 133 | | f_builtins | builtins namespace seen | | 134 | | | by this frame | | 135 +-----------+-----------------+---------------------------+-------+ 136 | | f_code | code object being | | 137 | | | executed in this frame | | 138 +-----------+-----------------+---------------------------+-------+ 139 | | f_exc_traceback | traceback if raised in | | 140 | | | this frame, or ``None`` | | 141 +-----------+-----------------+---------------------------+-------+ 142 | | f_exc_type | exception type if raised | | 143 | | | in this frame, or | | 144 | | | ``None`` | | 145 +-----------+-----------------+---------------------------+-------+ 146 | | f_exc_value | exception value if raised | | 147 | | | in this frame, or | | 148 | | | ``None`` | | 149 +-----------+-----------------+---------------------------+-------+ 150 | | f_globals | global namespace seen by | | 151 | | | this frame | | 152 +-----------+-----------------+---------------------------+-------+ 153 | | f_lasti | index of last attempted | | 154 | | | instruction in bytecode | | 155 +-----------+-----------------+---------------------------+-------+ 156 | | f_lineno | current line number in | | 157 | | | Python source code | | 158 +-----------+-----------------+---------------------------+-------+ 159 | | f_locals | local namespace seen by | | 160 | | | this frame | | 161 +-----------+-----------------+---------------------------+-------+ 162 | | f_restricted | 0 or 1 if frame is in | | 163 | | | restricted execution mode | | 164 +-----------+-----------------+---------------------------+-------+ 165 | | f_trace | tracing function for this | | 166 | | | frame, or ``None`` | | 167 +-----------+-----------------+---------------------------+-------+ 168 | code | co_argcount | number of arguments (not | | 169 | | | including \* or \*\* | | 170 | | | args) | | 171 +-----------+-----------------+---------------------------+-------+ 172 | | co_code | string of raw compiled | | 173 | | | bytecode | | 174 +-----------+-----------------+---------------------------+-------+ 175 | | co_consts | tuple of constants used | | 176 | | | in the bytecode | | 177 +-----------+-----------------+---------------------------+-------+ 178 | | co_filename | name of file in which | | 179 | | | this code object was | | 180 | | | created | | 181 +-----------+-----------------+---------------------------+-------+ 182 | | co_firstlineno | number of first line in | | 183 | | | Python source code | | 184 +-----------+-----------------+---------------------------+-------+ 185 | | co_flags | bitmap: 1=optimized ``|`` | | 186 | | | 2=newlocals ``|`` 4=\*arg | | 187 | | | ``|`` 8=\*\*arg | | 188 +-----------+-----------------+---------------------------+-------+ 189 | | co_lnotab | encoded mapping of line | | 190 | | | numbers to bytecode | | 191 | | | indices | | 192 +-----------+-----------------+---------------------------+-------+ 193 | | co_name | name with which this code | | 194 | | | object was defined | | 195 +-----------+-----------------+---------------------------+-------+ 196 | | co_names | tuple of names of local | | 197 | | | variables | | 198 +-----------+-----------------+---------------------------+-------+ 199 | | co_nlocals | number of local variables | | 200 +-----------+-----------------+---------------------------+-------+ 201 | | co_stacksize | virtual machine stack | | 202 | | | space required | | 203 +-----------+-----------------+---------------------------+-------+ 204 | | co_varnames | tuple of names of | | 205 | | | arguments and local | | 206 | | | variables | | 207 +-----------+-----------------+---------------------------+-------+ 208 | builtin | __doc__ | documentation string | | 209 +-----------+-----------------+---------------------------+-------+ 210 | | __name__ | original name of this | | 211 | | | function or method | | 212 +-----------+-----------------+---------------------------+-------+ 213 | | __self__ | instance to which a | | 214 | | | method is bound, or | | 215 | | | ``None`` | | 216 +-----------+-----------------+---------------------------+-------+ 217 218 Note: 219 220 (1) 221 .. versionchanged:: 2.2 222 :attr:`im_class` used to refer to the class that defined the method. 223 224 225 .. function:: getmembers(object[, predicate]) 226 227 Return all the members of an object in a list of (name, value) pairs sorted by 228 name. If the optional *predicate* argument is supplied, only members for which 229 the predicate returns a true value are included. 230 231 .. note:: 232 233 :func:`getmembers` does not return metaclass attributes when the argument 234 is a class (this behavior is inherited from the :func:`dir` function). 235 236 237 .. function:: getmoduleinfo(path) 238 239 Return a tuple of values that describe how Python will interpret the file 240 identified by *path* if it is a module, or ``None`` if it would not be 241 identified as a module. The return tuple is ``(name, suffix, mode, 242 module_type)``, where *name* is the name of the module without the name of 243 any enclosing package, *suffix* is the trailing part of the file name (which 244 may not be a dot-delimited extension), *mode* is the :func:`open` mode that 245 would be used (``'r'`` or ``'rb'``), and *module_type* is an integer giving 246 the type of the module. *module_type* will have a value which can be 247 compared to the constants defined in the :mod:`imp` module; see the 248 documentation for that module for more information on module types. 249 250 .. versionchanged:: 2.6 251 Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode, 252 module_type)``. 253 254 255 .. function:: getmodulename(path) 256 257 Return the name of the module named by the file *path*, without including the 258 names of enclosing packages. This uses the same algorithm as the interpreter 259 uses when searching for modules. If the name cannot be matched according to the 260 interpreter's rules, ``None`` is returned. 261 262 263 .. function:: ismodule(object) 264 265 Return true if the object is a module. 266 267 268 .. function:: isclass(object) 269 270 Return true if the object is a class, whether built-in or created in Python 271 code. 272 273 274 .. function:: ismethod(object) 275 276 Return true if the object is a bound or unbound method written in Python. 277 278 279 280 .. function:: isfunction(object) 281 282 Return true if the object is a Python function, which includes functions 283 created by a :term:`lambda` expression. 284 285 286 .. function:: isgeneratorfunction(object) 287 288 Return true if the object is a Python generator function. 289 290 .. versionadded:: 2.6 291 292 293 .. function:: isgenerator(object) 294 295 Return true if the object is a generator. 296 297 .. versionadded:: 2.6 298 299 300 .. function:: istraceback(object) 301 302 Return true if the object is a traceback. 303 304 305 .. function:: isframe(object) 306 307 Return true if the object is a frame. 308 309 310 .. function:: iscode(object) 311 312 Return true if the object is a code. 313 314 315 .. function:: isbuiltin(object) 316 317 Return true if the object is a built-in function or a bound built-in method. 318 319 320 .. function:: isroutine(object) 321 322 Return true if the object is a user-defined or built-in function or method. 323 324 325 .. function:: isabstract(object) 326 327 Return true if the object is an abstract base class. 328 329 .. versionadded:: 2.6 330 331 332 .. function:: ismethoddescriptor(object) 333 334 Return true if the object is a method descriptor, but not if 335 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin` 336 are true. 337 338 This is new as of Python 2.2, and, for example, is true of 339 ``int.__add__``. An object passing this test 340 has a :meth:`~object.__get__` method but not a :meth:`~object.__set__` 341 method, but beyond that the set of attributes varies. A 342 :attr:`~definition.__name__` attribute is usually 343 sensible, and :attr:`__doc__` often is. 344 345 Methods implemented via descriptors that also pass one of the other tests 346 return false from the :func:`ismethoddescriptor` test, simply because the 347 other tests promise more -- you can, e.g., count on having the 348 :attr:`im_func` attribute (etc) when an object passes :func:`ismethod`. 349 350 351 .. function:: isdatadescriptor(object) 352 353 Return true if the object is a data descriptor. 354 355 Data descriptors have both a :attr:`~object.__get__` and a :attr:`~object.__set__` method. 356 Examples are properties (defined in Python), getsets, and members. The 357 latter two are defined in C and there are more specific tests available for 358 those types, which is robust across Python implementations. Typically, data 359 descriptors will also have :attr:`~definition.__name__` and :attr:`__doc__` attributes 360 (properties, getsets, and members have both of these attributes), but this is 361 not guaranteed. 362 363 .. versionadded:: 2.3 364 365 366 .. function:: isgetsetdescriptor(object) 367 368 Return true if the object is a getset descriptor. 369 370 .. impl-detail:: 371 372 getsets are attributes defined in extension modules via 373 :c:type:`PyGetSetDef` structures. For Python implementations without such 374 types, this method will always return ``False``. 375 376 .. versionadded:: 2.5 377 378 379 .. function:: ismemberdescriptor(object) 380 381 Return true if the object is a member descriptor. 382 383 .. impl-detail:: 384 385 Member descriptors are attributes defined in extension modules via 386 :c:type:`PyMemberDef` structures. For Python implementations without such 387 types, this method will always return ``False``. 388 389 .. versionadded:: 2.5 390 391 392 .. _inspect-source: 393 394 Retrieving source code 395 ---------------------- 396 397 .. function:: getdoc(object) 398 399 Get the documentation string for an object, cleaned up with :func:`cleandoc`. 400 401 402 .. function:: getcomments(object) 403 404 Return in a single string any lines of comments immediately preceding the 405 object's source code (for a class, function, or method), or at the top of the 406 Python source file (if the object is a module). 407 408 409 .. function:: getfile(object) 410 411 Return the name of the (text or binary) file in which an object was defined. 412 This will fail with a :exc:`TypeError` if the object is a built-in module, 413 class, or function. 414 415 416 .. function:: getmodule(object) 417 418 Try to guess which module an object was defined in. 419 420 421 .. function:: getsourcefile(object) 422 423 Return the name of the Python source file in which an object was defined. This 424 will fail with a :exc:`TypeError` if the object is a built-in module, class, or 425 function. 426 427 428 .. function:: getsourcelines(object) 429 430 Return a list of source lines and starting line number for an object. The 431 argument may be a module, class, method, function, traceback, frame, or code 432 object. The source code is returned as a list of the lines corresponding to the 433 object and the line number indicates where in the original source file the first 434 line of code was found. An :exc:`IOError` is raised if the source code cannot 435 be retrieved. 436 437 438 .. function:: getsource(object) 439 440 Return the text of the source code for an object. The argument may be a module, 441 class, method, function, traceback, frame, or code object. The source code is 442 returned as a single string. An :exc:`IOError` is raised if the source code 443 cannot be retrieved. 444 445 446 .. function:: cleandoc(doc) 447 448 Clean up indentation from docstrings that are indented to line up with blocks 449 of code. 450 451 All leading whitespace is removed from the first line. Any leading whitespace 452 that can be uniformly removed from the second line onwards is removed. Empty 453 lines at the beginning and end are subsequently removed. Also, all tabs are 454 expanded to spaces. 455 456 .. versionadded:: 2.6 457 458 459 .. _inspect-classes-functions: 460 461 Classes and functions 462 --------------------- 463 464 465 .. function:: getclasstree(classes[, unique]) 466 467 Arrange the given list of classes into a hierarchy of nested lists. Where a 468 nested list appears, it contains classes derived from the class whose entry 469 immediately precedes the list. Each entry is a 2-tuple containing a class and a 470 tuple of its base classes. If the *unique* argument is true, exactly one entry 471 appears in the returned structure for each class in the given list. Otherwise, 472 classes using multiple inheritance and their descendants will appear multiple 473 times. 474 475 476 .. function:: getargspec(func) 477 478 Get the names and default values of a Python function's arguments. A tuple of 479 four things is returned: ``(args, varargs, keywords, defaults)``. *args* is a 480 list of the argument names (it may contain nested lists). *varargs* and 481 *keywords* are the names of the ``*`` and ``**`` arguments or 482 ``None``. *defaults* is a tuple of default argument values or ``None`` if there 483 are no default arguments; if this tuple has *n* elements, they correspond to 484 the last *n* elements listed in *args*. 485 486 .. versionchanged:: 2.6 487 Returns a :term:`named tuple` ``ArgSpec(args, varargs, keywords, 488 defaults)``. 489 490 491 .. function:: getargvalues(frame) 492 493 Get information about arguments passed into a particular frame. A tuple of 494 four things is returned: ``(args, varargs, keywords, locals)``. *args* is a 495 list of the argument names (it may contain nested lists). *varargs* and 496 *keywords* are the names of the ``*`` and ``**`` arguments or ``None``. 497 *locals* is the locals dictionary of the given frame. 498 499 .. versionchanged:: 2.6 500 Returns a :term:`named tuple` ``ArgInfo(args, varargs, keywords, 501 locals)``. 502 503 504 .. function:: formatargspec(args[, varargs, varkw, defaults, formatarg, formatvarargs, formatvarkw, formatvalue, join]) 505 506 Format a pretty argument spec from the four values returned by 507 :func:`getargspec`. The format\* arguments are the corresponding optional 508 formatting functions that are called to turn names and values into strings. 509 510 511 .. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue, join]) 512 513 Format a pretty argument spec from the four values returned by 514 :func:`getargvalues`. The format\* arguments are the corresponding optional 515 formatting functions that are called to turn names and values into strings. 516 517 518 .. function:: getmro(cls) 519 520 Return a tuple of class cls's base classes, including cls, in method resolution 521 order. No class appears more than once in this tuple. Note that the method 522 resolution order depends on cls's type. Unless a very peculiar user-defined 523 metatype is in use, cls will be the first element of the tuple. 524 525 526 .. function:: getcallargs(func[, *args][, **kwds]) 527 528 Bind the *args* and *kwds* to the argument names of the Python function or 529 method *func*, as if it was called with them. For bound methods, bind also the 530 first argument (typically named ``self``) to the associated instance. A dict 531 is returned, mapping the argument names (including the names of the ``*`` and 532 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of 533 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise 534 an exception because of incompatible signature, an exception of the same type 535 and the same or similar message is raised. For example:: 536 537 >>> from inspect import getcallargs 538 >>> def f(a, b=1, *pos, **named): 539 ... pass 540 >>> getcallargs(f, 1, 2, 3) 541 {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)} 542 >>> getcallargs(f, a=2, x=4) 543 {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()} 544 >>> getcallargs(f) 545 Traceback (most recent call last): 546 ... 547 TypeError: f() takes at least 1 argument (0 given) 548 549 .. versionadded:: 2.7 550 551 552 .. _inspect-stack: 553 554 The interpreter stack 555 --------------------- 556 557 When the following functions return "frame records," each record is a tuple of 558 six items: the frame object, the filename, the line number of the current line, 559 the function name, a list of lines of context from the source code, and the 560 index of the current line within that list. 561 562 .. note:: 563 564 Keeping references to frame objects, as found in the first element of the frame 565 records these functions return, can cause your program to create reference 566 cycles. Once a reference cycle has been created, the lifespan of all objects 567 which can be accessed from the objects which form the cycle can become much 568 longer even if Python's optional cycle detector is enabled. If such cycles must 569 be created, it is important to ensure they are explicitly broken to avoid the 570 delayed destruction of objects and increased memory consumption which occurs. 571 572 Though the cycle detector will catch these, destruction of the frames (and local 573 variables) can be made deterministic by removing the cycle in a 574 :keyword:`finally` clause. This is also important if the cycle detector was 575 disabled when Python was compiled or using :func:`gc.disable`. For example:: 576 577 def handle_stackframe_without_leak(): 578 frame = inspect.currentframe() 579 try: 580 # do something with the frame 581 finally: 582 del frame 583 584 The optional *context* argument supported by most of these functions specifies 585 the number of lines of context to return, which are centered around the current 586 line. 587 588 589 .. function:: getframeinfo(frame[, context]) 590 591 Get information about a frame or traceback object. A 5-tuple is returned, the 592 last five elements of the frame's frame record. 593 594 .. versionchanged:: 2.6 595 Returns a :term:`named tuple` ``Traceback(filename, lineno, function, 596 code_context, index)``. 597 598 599 .. function:: getouterframes(frame[, context]) 600 601 Get a list of frame records for a frame and all outer frames. These frames 602 represent the calls that lead to the creation of *frame*. The first entry in the 603 returned list represents *frame*; the last entry represents the outermost call 604 on *frame*'s stack. 605 606 607 .. function:: getinnerframes(traceback[, context]) 608 609 Get a list of frame records for a traceback's frame and all inner frames. These 610 frames represent calls made as a consequence of *frame*. The first entry in the 611 list represents *traceback*; the last entry represents where the exception was 612 raised. 613 614 615 .. function:: currentframe() 616 617 Return the frame object for the caller's stack frame. 618 619 .. impl-detail:: 620 621 This function relies on Python stack frame support in the interpreter, 622 which isn't guaranteed to exist in all implementations of Python. If 623 running in an implementation without Python stack frame support this 624 function returns ``None``. 625 626 627 .. function:: stack([context]) 628 629 Return a list of frame records for the caller's stack. The first entry in the 630 returned list represents the caller; the last entry represents the outermost 631 call on the stack. 632 633 634 .. function:: trace([context]) 635 636 Return a list of frame records for the stack between the current frame and the 637 frame in which an exception currently being handled was raised in. The first 638 entry in the list represents the caller; the last entry represents where the 639 exception was raised. 640 641