blob: 7893b69246e238b70a05e797f6681834a5b97207 [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
31class or module. The eleven functions whose names begin with "is" are mainly
32provided 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+-----------+-----------------+---------------------------+-------+
57| | im_func | function object | |
58| | | containing implementation | |
59| | | of method | |
60+-----------+-----------------+---------------------------+-------+
61| | im_self | instance to which this | |
62| | | method is bound, or | |
63| | | ``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+-----------+-----------------+---------------------------+-------+
84| traceback | tb_frame | frame object at this | |
85| | | level | |
86+-----------+-----------------+---------------------------+-------+
87| | tb_lasti | index of last attempted | |
88| | | instruction in bytecode | |
89+-----------+-----------------+---------------------------+-------+
90| | tb_lineno | current line number in | |
91| | | Python source code | |
92+-----------+-----------------+---------------------------+-------+
93| | tb_next | next inner traceback | |
94| | | object (called by this | |
95| | | level) | |
96+-----------+-----------------+---------------------------+-------+
97| frame | f_back | next outer frame object | |
98| | | (this frame's caller) | |
99+-----------+-----------------+---------------------------+-------+
100| | f_builtins | built-in namespace seen | |
101| | | by this frame | |
102+-----------+-----------------+---------------------------+-------+
103| | f_code | code object being | |
104| | | executed in this frame | |
105+-----------+-----------------+---------------------------+-------+
106| | f_exc_traceback | traceback if raised in | |
107| | | this frame, or ``None`` | |
108+-----------+-----------------+---------------------------+-------+
109| | f_exc_type | exception type if raised | |
110| | | in this frame, or | |
111| | | ``None`` | |
112+-----------+-----------------+---------------------------+-------+
113| | f_exc_value | exception value if raised | |
114| | | in this frame, or | |
115| | | ``None`` | |
116+-----------+-----------------+---------------------------+-------+
117| | f_globals | global namespace seen by | |
118| | | this frame | |
119+-----------+-----------------+---------------------------+-------+
120| | f_lasti | index of last attempted | |
121| | | instruction in bytecode | |
122+-----------+-----------------+---------------------------+-------+
123| | f_lineno | current line number in | |
124| | | Python source code | |
125+-----------+-----------------+---------------------------+-------+
126| | f_locals | local namespace seen by | |
127| | | this frame | |
128+-----------+-----------------+---------------------------+-------+
129| | f_restricted | 0 or 1 if frame is in | |
130| | | restricted execution mode | |
131+-----------+-----------------+---------------------------+-------+
132| | f_trace | tracing function for this | |
133| | | frame, or ``None`` | |
134+-----------+-----------------+---------------------------+-------+
135| code | co_argcount | number of arguments (not | |
136| | | including \* or \*\* | |
137| | | args) | |
138+-----------+-----------------+---------------------------+-------+
139| | co_code | string of raw compiled | |
140| | | bytecode | |
141+-----------+-----------------+---------------------------+-------+
142| | co_consts | tuple of constants used | |
143| | | in the bytecode | |
144+-----------+-----------------+---------------------------+-------+
145| | co_filename | name of file in which | |
146| | | this code object was | |
147| | | created | |
148+-----------+-----------------+---------------------------+-------+
149| | co_firstlineno | number of first line in | |
150| | | Python source code | |
151+-----------+-----------------+---------------------------+-------+
152| | co_flags | bitmap: 1=optimized ``|`` | |
153| | | 2=newlocals ``|`` 4=\*arg | |
154| | | ``|`` 8=\*\*arg | |
155+-----------+-----------------+---------------------------+-------+
156| | co_lnotab | encoded mapping of line | |
157| | | numbers to bytecode | |
158| | | indices | |
159+-----------+-----------------+---------------------------+-------+
160| | co_name | name with which this code | |
161| | | object was defined | |
162+-----------+-----------------+---------------------------+-------+
163| | co_names | tuple of names of local | |
164| | | variables | |
165+-----------+-----------------+---------------------------+-------+
166| | co_nlocals | number of local variables | |
167+-----------+-----------------+---------------------------+-------+
168| | co_stacksize | virtual machine stack | |
169| | | space required | |
170+-----------+-----------------+---------------------------+-------+
171| | co_varnames | tuple of names of | |
172| | | arguments and local | |
173| | | variables | |
174+-----------+-----------------+---------------------------+-------+
175| builtin | __doc__ | documentation string | |
176+-----------+-----------------+---------------------------+-------+
177| | __name__ | original name of this | |
178| | | function or method | |
179+-----------+-----------------+---------------------------+-------+
180| | __self__ | instance to which a | |
181| | | method is bound, or | |
182| | | ``None`` | |
183+-----------+-----------------+---------------------------+-------+
184
185Note:
186
187(1)
188 .. versionchanged:: 2.2
189 :attr:`im_class` used to refer to the class that defined the method.
190
191
192.. function:: getmembers(object[, predicate])
193
194 Return all the members of an object in a list of (name, value) pairs sorted by
195 name. If the optional *predicate* argument is supplied, only members for which
196 the predicate returns a true value are included.
197
Georg Brandl91a48082008-01-06 15:48:20 +0000198 .. note::
199
200 :func:`getmembers` does not return metaclass attributes when the argument
201 is a class (this behavior is inherited from the :func:`dir` function).
202
Georg Brandl8ec7f652007-08-15 14:28:01 +0000203
204.. function:: getmoduleinfo(path)
205
206 Return a tuple of values that describe how Python will interpret the file
207 identified by *path* if it is a module, or ``None`` if it would not be
208 identified as a module. The return tuple is ``(name, suffix, mode, mtype)``,
209 where *name* is the name of the module without the name of any enclosing
210 package, *suffix* is the trailing part of the file name (which may not be a
211 dot-delimited extension), *mode* is the :func:`open` mode that would be used
212 (``'r'`` or ``'rb'``), and *mtype* is an integer giving the type of the
213 module. *mtype* will have a value which can be compared to the constants
214 defined in the :mod:`imp` module; see the documentation for that module for
215 more information on module types.
216
Georg Brandle3c3db52008-01-11 09:55:53 +0000217 .. versionchanged:: 2.6
218 Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode,
219 module_type)``.
220
Georg Brandl8ec7f652007-08-15 14:28:01 +0000221
222.. function:: getmodulename(path)
223
224 Return the name of the module named by the file *path*, without including the
225 names of enclosing packages. This uses the same algorithm as the interpreter
226 uses when searching for modules. If the name cannot be matched according to the
227 interpreter's rules, ``None`` is returned.
228
229
230.. function:: ismodule(object)
231
232 Return true if the object is a module.
233
234
235.. function:: isclass(object)
236
237 Return true if the object is a class.
238
239
240.. function:: ismethod(object)
241
242 Return true if the object is a method.
243
244
245.. function:: isfunction(object)
246
Georg Brandl584265b2007-12-02 14:58:50 +0000247 Return true if the object is a Python function or unnamed (:term:`lambda`) function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000248
249
250.. function:: istraceback(object)
251
252 Return true if the object is a traceback.
253
254
255.. function:: isframe(object)
256
257 Return true if the object is a frame.
258
259
260.. function:: iscode(object)
261
262 Return true if the object is a code.
263
264
265.. function:: isbuiltin(object)
266
267 Return true if the object is a built-in function.
268
269
270.. function:: isroutine(object)
271
272 Return true if the object is a user-defined or built-in function or method.
273
274
275.. function:: ismethoddescriptor(object)
276
Georg Brandl5c174bb2007-10-21 10:32:54 +0000277 Return true if the object is a method descriptor, but not if :func:`ismethod`
278 or :func:`isclass` or :func:`isfunction` are true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000279
Georg Brandl5c174bb2007-10-21 10:32:54 +0000280 This is new as of Python 2.2, and, for example, is true of
281 ``int.__add__``. An object passing this test has a :attr:`__get__` attribute
282 but not a :attr:`__set__` attribute, but beyond that the set of attributes
283 varies. :attr:`__name__` is usually sensible, and :attr:`__doc__` often is.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000284
Georg Brandl5c174bb2007-10-21 10:32:54 +0000285 Methods implemented via descriptors that also pass one of the other tests
286 return false from the :func:`ismethoddescriptor` test, simply because the
287 other tests promise more -- you can, e.g., count on having the
288 :attr:`im_func` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000289
290
291.. function:: isdatadescriptor(object)
292
293 Return true if the object is a data descriptor.
294
Georg Brandl5c174bb2007-10-21 10:32:54 +0000295 Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute.
296 Examples are properties (defined in Python), getsets, and members. The
297 latter two are defined in C and there are more specific tests available for
298 those types, which is robust across Python implementations. Typically, data
299 descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes
300 (properties, getsets, and members have both of these attributes), but this is
301 not guaranteed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000302
303 .. versionadded:: 2.3
304
305
306.. function:: isgetsetdescriptor(object)
307
308 Return true if the object is a getset descriptor.
309
310 getsets are attributes defined in extension modules via ``PyGetSetDef``
311 structures. For Python implementations without such types, this method will
312 always return ``False``.
313
314 .. versionadded:: 2.5
315
316
317.. function:: ismemberdescriptor(object)
318
319 Return true if the object is a member descriptor.
320
321 Member descriptors are attributes defined in extension modules via
Georg Brandl5c174bb2007-10-21 10:32:54 +0000322 ``PyMemberDef`` structures. For Python implementations without such types,
323 this method will always return ``False``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000324
325 .. versionadded:: 2.5
326
327
328.. _inspect-source:
329
330Retrieving source code
331----------------------
332
333
334.. function:: getdoc(object)
335
336 Get the documentation string for an object. All tabs are expanded to spaces. To
337 clean up docstrings that are indented to line up with blocks of code, any
338 whitespace than can be uniformly removed from the second line onwards is
339 removed.
340
341
342.. function:: getcomments(object)
343
344 Return in a single string any lines of comments immediately preceding the
345 object's source code (for a class, function, or method), or at the top of the
346 Python source file (if the object is a module).
347
348
349.. function:: getfile(object)
350
351 Return the name of the (text or binary) file in which an object was defined.
352 This will fail with a :exc:`TypeError` if the object is a built-in module,
353 class, or function.
354
355
356.. function:: getmodule(object)
357
358 Try to guess which module an object was defined in.
359
360
361.. function:: getsourcefile(object)
362
363 Return the name of the Python source file in which an object was defined. This
364 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
365 function.
366
367
368.. function:: getsourcelines(object)
369
370 Return a list of source lines and starting line number for an object. The
371 argument may be a module, class, method, function, traceback, frame, or code
372 object. The source code is returned as a list of the lines corresponding to the
373 object and the line number indicates where in the original source file the first
374 line of code was found. An :exc:`IOError` is raised if the source code cannot
375 be retrieved.
376
377
378.. function:: getsource(object)
379
380 Return the text of the source code for an object. The argument may be a module,
381 class, method, function, traceback, frame, or code object. The source code is
382 returned as a single string. An :exc:`IOError` is raised if the source code
383 cannot be retrieved.
384
385
386.. _inspect-classes-functions:
387
388Classes and functions
389---------------------
390
391
392.. function:: getclasstree(classes[, unique])
393
394 Arrange the given list of classes into a hierarchy of nested lists. Where a
395 nested list appears, it contains classes derived from the class whose entry
396 immediately precedes the list. Each entry is a 2-tuple containing a class and a
397 tuple of its base classes. If the *unique* argument is true, exactly one entry
398 appears in the returned structure for each class in the given list. Otherwise,
399 classes using multiple inheritance and their descendants will appear multiple
400 times.
401
402
403.. function:: getargspec(func)
404
405 Get the names and default values of a function's arguments. A tuple of four
406 things is returned: ``(args, varargs, varkw, defaults)``. *args* is a list of
407 the argument names (it may contain nested lists). *varargs* and *varkw* are the
408 names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a tuple of
409 default argument values or None if there are no default arguments; if this tuple
410 has *n* elements, they correspond to the last *n* elements listed in *args*.
411
Georg Brandle3c3db52008-01-11 09:55:53 +0000412 .. versionchanged:: 2.6
413 Returns a :term:`named tuple` ``ArgSpec(args, varargs, keywords,
414 defaults)``.
415
Georg Brandl8ec7f652007-08-15 14:28:01 +0000416
417.. function:: getargvalues(frame)
418
419 Get information about arguments passed into a particular frame. A tuple of four
420 things is returned: ``(args, varargs, varkw, locals)``. *args* is a list of the
421 argument names (it may contain nested lists). *varargs* and *varkw* are the
422 names of the ``*`` and ``**`` arguments or ``None``. *locals* is the locals
423 dictionary of the given frame.
424
Georg Brandle3c3db52008-01-11 09:55:53 +0000425 .. versionchanged:: 2.6
426 Returns a :term:`named tuple` ``ArgInfo(args, varargs, keywords,
427 locals)``.
428
Georg Brandl8ec7f652007-08-15 14:28:01 +0000429
430.. function:: formatargspec(args[, varargs, varkw, defaults, formatarg, formatvarargs, formatvarkw, formatvalue, join])
431
432 Format a pretty argument spec from the four values returned by
433 :func:`getargspec`. The format\* arguments are the corresponding optional
434 formatting functions that are called to turn names and values into strings.
435
436
437.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue, join])
438
439 Format a pretty argument spec from the four values returned by
440 :func:`getargvalues`. The format\* arguments are the corresponding optional
441 formatting functions that are called to turn names and values into strings.
442
443
444.. function:: getmro(cls)
445
446 Return a tuple of class cls's base classes, including cls, in method resolution
447 order. No class appears more than once in this tuple. Note that the method
448 resolution order depends on cls's type. Unless a very peculiar user-defined
449 metatype is in use, cls will be the first element of the tuple.
450
451
452.. _inspect-stack:
453
454The interpreter stack
455---------------------
456
457When the following functions return "frame records," each record is a tuple of
458six items: the frame object, the filename, the line number of the current line,
459the function name, a list of lines of context from the source code, and the
460index of the current line within that list.
461
462.. warning::
463
464 Keeping references to frame objects, as found in the first element of the frame
465 records these functions return, can cause your program to create reference
466 cycles. Once a reference cycle has been created, the lifespan of all objects
467 which can be accessed from the objects which form the cycle can become much
468 longer even if Python's optional cycle detector is enabled. If such cycles must
469 be created, it is important to ensure they are explicitly broken to avoid the
470 delayed destruction of objects and increased memory consumption which occurs.
471
472 Though the cycle detector will catch these, destruction of the frames (and local
473 variables) can be made deterministic by removing the cycle in a
474 :keyword:`finally` clause. This is also important if the cycle detector was
475 disabled when Python was compiled or using :func:`gc.disable`. For example::
476
477 def handle_stackframe_without_leak():
478 frame = inspect.currentframe()
479 try:
480 # do something with the frame
481 finally:
482 del frame
483
484The optional *context* argument supported by most of these functions specifies
485the number of lines of context to return, which are centered around the current
486line.
487
488
489.. function:: getframeinfo(frame[, context])
490
491 Get information about a frame or traceback object. A 5-tuple is returned, the
492 last five elements of the frame's frame record.
493
Georg Brandle3c3db52008-01-11 09:55:53 +0000494 .. versionchanged:: 2.6
495 Returns a :term:`named tuple` ``Traceback(filename, lineno, function,
496 code_context, index)``.
497
Georg Brandl8ec7f652007-08-15 14:28:01 +0000498
499.. function:: getouterframes(frame[, context])
500
501 Get a list of frame records for a frame and all outer frames. These frames
502 represent the calls that lead to the creation of *frame*. The first entry in the
503 returned list represents *frame*; the last entry represents the outermost call
504 on *frame*'s stack.
505
506
507.. function:: getinnerframes(traceback[, context])
508
509 Get a list of frame records for a traceback's frame and all inner frames. These
510 frames represent calls made as a consequence of *frame*. The first entry in the
511 list represents *traceback*; the last entry represents where the exception was
512 raised.
513
514
515.. function:: currentframe()
516
517 Return the frame object for the caller's stack frame.
518
519
520.. function:: stack([context])
521
522 Return a list of frame records for the caller's stack. The first entry in the
523 returned list represents the caller; the last entry represents the outermost
524 call on the stack.
525
526
527.. function:: trace([context])
528
529 Return a list of frame records for the stack between the current frame and the
530 frame in which an exception currently being handled was raised in. The first
531 entry in the list represents the caller; the last entry represents where the
532 exception was raised.
533