blob: 98ecbcb1de45ba831c5c90749e84ba4ca996b803 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl116aa622007-08-15 14:28:22 +000011The :mod:`inspect` module provides several useful functions to help get
12information about live objects such as modules, classes, methods, functions,
13tracebacks, frame objects, and code objects. For example, it can help you
14examine the contents of a class, retrieve the source code of a method, extract
15and format the argument list for a function, or get all the information you need
16to display a detailed traceback.
17
18There are four main kinds of services provided by this module: type checking,
19getting source code, inspecting classes and functions, and examining the
20interpreter stack.
21
22
23.. _inspect-types:
24
25Types and members
26-----------------
27
28The :func:`getmembers` function retrieves the members of an object such as a
Christian Heimes78644762008-03-04 23:39:23 +000029class or module. The sixteen functions whose names begin with "is" are mainly
Georg Brandl116aa622007-08-15 14:28:22 +000030provided as convenient choices for the second argument to :func:`getmembers`.
31They also help you determine when you can expect to find the following special
32attributes:
33
Georg Brandl55ac8f02007-09-01 13:51:09 +000034+-----------+-----------------+---------------------------+
35| Type | Attribute | Description |
36+===========+=================+===========================+
37| module | __doc__ | documentation string |
38+-----------+-----------------+---------------------------+
39| | __file__ | filename (missing for |
40| | | built-in modules) |
41+-----------+-----------------+---------------------------+
42| class | __doc__ | documentation string |
43+-----------+-----------------+---------------------------+
44| | __module__ | name of module in which |
45| | | this class was defined |
46+-----------+-----------------+---------------------------+
47| method | __doc__ | documentation string |
48+-----------+-----------------+---------------------------+
49| | __name__ | name with which this |
50| | | method was defined |
51+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000052| | __func__ | function object |
Georg Brandl55ac8f02007-09-01 13:51:09 +000053| | | containing implementation |
54| | | of method |
55+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000056| | __self__ | instance to which this |
Georg Brandl55ac8f02007-09-01 13:51:09 +000057| | | method is bound, or |
58| | | ``None`` |
59+-----------+-----------------+---------------------------+
60| function | __doc__ | documentation string |
61+-----------+-----------------+---------------------------+
62| | __name__ | name with which this |
63| | | function was defined |
64+-----------+-----------------+---------------------------+
65| | __code__ | code object containing |
66| | | compiled function |
Georg Brandl9afde1c2007-11-01 20:32:30 +000067| | | :term:`bytecode` |
Georg Brandl55ac8f02007-09-01 13:51:09 +000068+-----------+-----------------+---------------------------+
69| | __defaults__ | tuple of any default |
70| | | values for arguments |
71+-----------+-----------------+---------------------------+
72| | __globals__ | global namespace in which |
73| | | this function was defined |
74+-----------+-----------------+---------------------------+
75| traceback | tb_frame | frame object at this |
76| | | level |
77+-----------+-----------------+---------------------------+
78| | tb_lasti | index of last attempted |
79| | | instruction in bytecode |
80+-----------+-----------------+---------------------------+
81| | tb_lineno | current line number in |
82| | | Python source code |
83+-----------+-----------------+---------------------------+
84| | tb_next | next inner traceback |
85| | | object (called by this |
86| | | level) |
87+-----------+-----------------+---------------------------+
88| frame | f_back | next outer frame object |
89| | | (this frame's caller) |
90+-----------+-----------------+---------------------------+
91| | f_builtins | built-in namespace seen |
92| | | by this frame |
93+-----------+-----------------+---------------------------+
94| | f_code | code object being |
95| | | executed in this frame |
96+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +000097| | f_globals | global namespace seen by |
98| | | this frame |
99+-----------+-----------------+---------------------------+
100| | f_lasti | index of last attempted |
101| | | instruction in bytecode |
102+-----------+-----------------+---------------------------+
103| | f_lineno | current line number in |
104| | | Python source code |
105+-----------+-----------------+---------------------------+
106| | f_locals | local namespace seen by |
107| | | this frame |
108+-----------+-----------------+---------------------------+
109| | f_restricted | 0 or 1 if frame is in |
110| | | restricted execution mode |
111+-----------+-----------------+---------------------------+
112| | f_trace | tracing function for this |
113| | | frame, or ``None`` |
114+-----------+-----------------+---------------------------+
115| code | co_argcount | number of arguments (not |
116| | | including \* or \*\* |
117| | | args) |
118+-----------+-----------------+---------------------------+
119| | co_code | string of raw compiled |
120| | | bytecode |
121+-----------+-----------------+---------------------------+
122| | co_consts | tuple of constants used |
123| | | in the bytecode |
124+-----------+-----------------+---------------------------+
125| | co_filename | name of file in which |
126| | | this code object was |
127| | | created |
128+-----------+-----------------+---------------------------+
129| | co_firstlineno | number of first line in |
130| | | Python source code |
131+-----------+-----------------+---------------------------+
132| | co_flags | bitmap: 1=optimized ``|`` |
133| | | 2=newlocals ``|`` 4=\*arg |
134| | | ``|`` 8=\*\*arg |
135+-----------+-----------------+---------------------------+
136| | co_lnotab | encoded mapping of line |
137| | | numbers to bytecode |
138| | | indices |
139+-----------+-----------------+---------------------------+
140| | co_name | name with which this code |
141| | | object was defined |
142+-----------+-----------------+---------------------------+
143| | co_names | tuple of names of local |
144| | | variables |
145+-----------+-----------------+---------------------------+
146| | co_nlocals | number of local variables |
147+-----------+-----------------+---------------------------+
148| | co_stacksize | virtual machine stack |
149| | | space required |
150+-----------+-----------------+---------------------------+
151| | co_varnames | tuple of names of |
152| | | arguments and local |
153| | | variables |
154+-----------+-----------------+---------------------------+
155| builtin | __doc__ | documentation string |
156+-----------+-----------------+---------------------------+
157| | __name__ | original name of this |
158| | | function or method |
159+-----------+-----------------+---------------------------+
160| | __self__ | instance to which a |
161| | | method is bound, or |
162| | | ``None`` |
163+-----------+-----------------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165
166.. function:: getmembers(object[, predicate])
167
168 Return all the members of an object in a list of (name, value) pairs sorted by
169 name. If the optional *predicate* argument is supplied, only members for which
170 the predicate returns a true value are included.
171
Christian Heimes7f044312008-01-06 17:05:40 +0000172 .. note::
173
174 :func:`getmembers` does not return metaclass attributes when the argument
175 is a class (this behavior is inherited from the :func:`dir` function).
176
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178.. function:: getmoduleinfo(path)
179
Christian Heimes25bb7832008-01-11 16:17:00 +0000180 Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode,
181 module_type)`` of values that describe how Python will interpret the file
Georg Brandl116aa622007-08-15 14:28:22 +0000182 identified by *path* if it is a module, or ``None`` if it would not be
183 identified as a module. The return tuple is ``(name, suffix, mode, mtype)``,
184 where *name* is the name of the module without the name of any enclosing
185 package, *suffix* is the trailing part of the file name (which may not be a
186 dot-delimited extension), *mode* is the :func:`open` mode that would be used
187 (``'r'`` or ``'rb'``), and *mtype* is an integer giving the type of the
188 module. *mtype* will have a value which can be compared to the constants
189 defined in the :mod:`imp` module; see the documentation for that module for
190 more information on module types.
191
192
193.. function:: getmodulename(path)
194
195 Return the name of the module named by the file *path*, without including the
196 names of enclosing packages. This uses the same algorithm as the interpreter
197 uses when searching for modules. If the name cannot be matched according to the
198 interpreter's rules, ``None`` is returned.
199
200
201.. function:: ismodule(object)
202
203 Return true if the object is a module.
204
205
206.. function:: isclass(object)
207
208 Return true if the object is a class.
209
210
211.. function:: ismethod(object)
212
213 Return true if the object is a method.
214
215
216.. function:: isfunction(object)
217
Christian Heimesd8654cf2007-12-02 15:22:16 +0000218 Return true if the object is a Python function or unnamed (:term:`lambda`) function.
Georg Brandl116aa622007-08-15 14:28:22 +0000219
220
Christian Heimes7131fd92008-02-19 14:21:46 +0000221.. function:: isgeneratorfunction(object)
222
223 Return true if the object is a Python generator function.
224
225
226.. function:: isgenerator(object)
227
228 Return true if the object is a generator.
229
230
Georg Brandl116aa622007-08-15 14:28:22 +0000231.. function:: istraceback(object)
232
233 Return true if the object is a traceback.
234
235
236.. function:: isframe(object)
237
238 Return true if the object is a frame.
239
240
241.. function:: iscode(object)
242
243 Return true if the object is a code.
244
245
246.. function:: isbuiltin(object)
247
248 Return true if the object is a built-in function.
249
250
251.. function:: isroutine(object)
252
253 Return true if the object is a user-defined or built-in function or method.
254
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000255.. function:: isabstract(object)
256
257 Return true if the object is an abstract base class.
258
Georg Brandl116aa622007-08-15 14:28:22 +0000259
260.. function:: ismethoddescriptor(object)
261
Georg Brandl9afde1c2007-11-01 20:32:30 +0000262 Return true if the object is a method descriptor, but not if :func:`ismethod`
263 or :func:`isclass` or :func:`isfunction` are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000264
Georg Brandle6bcc912008-05-12 18:05:20 +0000265 This, for example, is true of ``int.__add__``. An object passing this test
266 has a :attr:`__get__` attribute but not a :attr:`__set__` attribute, but
267 beyond that the set of attributes varies. :attr:`__name__` is usually
268 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000269
Georg Brandl9afde1c2007-11-01 20:32:30 +0000270 Methods implemented via descriptors that also pass one of the other tests
271 return false from the :func:`ismethoddescriptor` test, simply because the
272 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000273 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000274
275
276.. function:: isdatadescriptor(object)
277
278 Return true if the object is a data descriptor.
279
Georg Brandl9afde1c2007-11-01 20:32:30 +0000280 Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute.
281 Examples are properties (defined in Python), getsets, and members. The
282 latter two are defined in C and there are more specific tests available for
283 those types, which is robust across Python implementations. Typically, data
284 descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes
285 (properties, getsets, and members have both of these attributes), but this is
286 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000287
Georg Brandl116aa622007-08-15 14:28:22 +0000288
289.. function:: isgetsetdescriptor(object)
290
291 Return true if the object is a getset descriptor.
292
293 getsets are attributes defined in extension modules via ``PyGetSetDef``
294 structures. For Python implementations without such types, this method will
295 always return ``False``.
296
Georg Brandl116aa622007-08-15 14:28:22 +0000297
298.. function:: ismemberdescriptor(object)
299
300 Return true if the object is a member descriptor.
301
302 Member descriptors are attributes defined in extension modules via
Georg Brandl9afde1c2007-11-01 20:32:30 +0000303 ``PyMemberDef`` structures. For Python implementations without such types,
304 this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000305
Georg Brandl116aa622007-08-15 14:28:22 +0000306
307.. _inspect-source:
308
309Retrieving source code
310----------------------
311
Georg Brandl116aa622007-08-15 14:28:22 +0000312.. function:: getdoc(object)
313
Georg Brandl0c77a822008-06-10 16:37:50 +0000314 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Georg Brandl116aa622007-08-15 14:28:22 +0000315
316
317.. function:: getcomments(object)
318
319 Return in a single string any lines of comments immediately preceding the
320 object's source code (for a class, function, or method), or at the top of the
321 Python source file (if the object is a module).
322
323
324.. function:: getfile(object)
325
326 Return the name of the (text or binary) file in which an object was defined.
327 This will fail with a :exc:`TypeError` if the object is a built-in module,
328 class, or function.
329
330
331.. function:: getmodule(object)
332
333 Try to guess which module an object was defined in.
334
335
336.. function:: getsourcefile(object)
337
338 Return the name of the Python source file in which an object was defined. This
339 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
340 function.
341
342
343.. function:: getsourcelines(object)
344
345 Return a list of source lines and starting line number for an object. The
346 argument may be a module, class, method, function, traceback, frame, or code
347 object. The source code is returned as a list of the lines corresponding to the
348 object and the line number indicates where in the original source file the first
349 line of code was found. An :exc:`IOError` is raised if the source code cannot
350 be retrieved.
351
352
353.. function:: getsource(object)
354
355 Return the text of the source code for an object. The argument may be a module,
356 class, method, function, traceback, frame, or code object. The source code is
357 returned as a single string. An :exc:`IOError` is raised if the source code
358 cannot be retrieved.
359
360
Georg Brandl0c77a822008-06-10 16:37:50 +0000361.. function:: cleandoc(doc)
362
363 Clean up indentation from docstrings that are indented to line up with blocks
364 of code. Any whitespace that can be uniformly removed from the second line
365 onwards is removed. Also, all tabs are expanded to spaces.
366
367 .. versionadded:: 2.6
368
369
Georg Brandl116aa622007-08-15 14:28:22 +0000370.. _inspect-classes-functions:
371
372Classes and functions
373---------------------
374
375
376.. function:: getclasstree(classes[, unique])
377
378 Arrange the given list of classes into a hierarchy of nested lists. Where a
379 nested list appears, it contains classes derived from the class whose entry
380 immediately precedes the list. Each entry is a 2-tuple containing a class and a
381 tuple of its base classes. If the *unique* argument is true, exactly one entry
382 appears in the returned structure for each class in the given list. Otherwise,
383 classes using multiple inheritance and their descendants will appear multiple
384 times.
385
386
387.. function:: getargspec(func)
388
Christian Heimes25bb7832008-01-11 16:17:00 +0000389 Get the names and default values of a function's arguments. A
390 :term:`named tuple` ``ArgSpec(args, varargs, keywords,
391 defaults)`` is returned. *args* is a list of
Georg Brandl138bcb52007-09-12 19:04:21 +0000392 the argument names. *varargs* and *varkw* are the names of the ``*`` and
393 ``**`` arguments or ``None``. *defaults* is a tuple of default argument
394 values or None if there are no default arguments; if this tuple has *n*
395 elements, they correspond to the last *n* elements listed in *args*.
396
397 .. deprecated:: 3.0
398 Use :func:`getfullargspec` instead, which provides information about
399 keyword-only arguments.
400
401
402.. function:: getfullargspec(func)
403
Christian Heimes25bb7832008-01-11 16:17:00 +0000404 Get the names and default values of a function's arguments. A :term:`named tuple`
405 is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000406
Christian Heimes25bb7832008-01-11 16:17:00 +0000407 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000408
409 *args* is a list of the argument names. *varargs* and *varkw* are the names
410 of the ``*`` and ``**`` arguments or ``None``. *defaults* is an n-tuple of
411 the default values of the last n arguments. *kwonlyargs* is a list of
412 keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
413 from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
414 names to annotations.
415
416 The first four items in the tuple correspond to :func:`getargspec`.
Georg Brandl116aa622007-08-15 14:28:22 +0000417
418
419.. function:: getargvalues(frame)
420
Christian Heimes25bb7832008-01-11 16:17:00 +0000421 Get information about arguments passed into a particular frame. A :term:`named tuple`
422 ``ArgInfo(args, varargs, keywords, locals)`` is returned. *args* is a list of the
Georg Brandl116aa622007-08-15 14:28:22 +0000423 argument names (it may contain nested lists). *varargs* and *varkw* are the
424 names of the ``*`` and ``**`` arguments or ``None``. *locals* is the locals
425 dictionary of the given frame.
426
427
428.. function:: formatargspec(args[, varargs, varkw, defaults, formatarg, formatvarargs, formatvarkw, formatvalue, join])
429
430 Format a pretty argument spec from the four values returned by
431 :func:`getargspec`. The format\* arguments are the corresponding optional
432 formatting functions that are called to turn names and values into strings.
433
434
435.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue, join])
436
437 Format a pretty argument spec from the four values returned by
438 :func:`getargvalues`. The format\* arguments are the corresponding optional
439 formatting functions that are called to turn names and values into strings.
440
441
442.. function:: getmro(cls)
443
444 Return a tuple of class cls's base classes, including cls, in method resolution
445 order. No class appears more than once in this tuple. Note that the method
446 resolution order depends on cls's type. Unless a very peculiar user-defined
447 metatype is in use, cls will be the first element of the tuple.
448
449
450.. _inspect-stack:
451
452The interpreter stack
453---------------------
454
455When the following functions return "frame records," each record is a tuple of
456six items: the frame object, the filename, the line number of the current line,
457the function name, a list of lines of context from the source code, and the
458index of the current line within that list.
459
460.. warning::
461
462 Keeping references to frame objects, as found in the first element of the frame
463 records these functions return, can cause your program to create reference
464 cycles. Once a reference cycle has been created, the lifespan of all objects
465 which can be accessed from the objects which form the cycle can become much
466 longer even if Python's optional cycle detector is enabled. If such cycles must
467 be created, it is important to ensure they are explicitly broken to avoid the
468 delayed destruction of objects and increased memory consumption which occurs.
469
470 Though the cycle detector will catch these, destruction of the frames (and local
471 variables) can be made deterministic by removing the cycle in a
472 :keyword:`finally` clause. This is also important if the cycle detector was
473 disabled when Python was compiled or using :func:`gc.disable`. For example::
474
475 def handle_stackframe_without_leak():
476 frame = inspect.currentframe()
477 try:
478 # do something with the frame
479 finally:
480 del frame
481
482The optional *context* argument supported by most of these functions specifies
483the number of lines of context to return, which are centered around the current
484line.
485
486
487.. function:: getframeinfo(frame[, context])
488
Christian Heimes25bb7832008-01-11 16:17:00 +0000489 Get information about a frame or traceback object. A :term:`named tuple`
490 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000491
492
493.. function:: getouterframes(frame[, context])
494
495 Get a list of frame records for a frame and all outer frames. These frames
496 represent the calls that lead to the creation of *frame*. The first entry in the
497 returned list represents *frame*; the last entry represents the outermost call
498 on *frame*'s stack.
499
500
501.. function:: getinnerframes(traceback[, context])
502
503 Get a list of frame records for a traceback's frame and all inner frames. These
504 frames represent calls made as a consequence of *frame*. The first entry in the
505 list represents *traceback*; the last entry represents where the exception was
506 raised.
507
508
509.. function:: currentframe()
510
511 Return the frame object for the caller's stack frame.
512
513
514.. function:: stack([context])
515
516 Return a list of frame records for the caller's stack. The first entry in the
517 returned list represents the caller; the last entry represents the outermost
518 call on the stack.
519
520
521.. function:: trace([context])
522
523 Return a list of frame records for the stack between the current frame and the
524 frame in which an exception currently being handled was raised in. The first
525 entry in the list represents the caller; the last entry represents where the
526 exception was raised.
527