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