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