blob: c1f0f009399e9994117e01953bf12f062094aeb1 [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
217
218.. function:: getmodulename(path)
219
220 Return the name of the module named by the file *path*, without including the
221 names of enclosing packages. This uses the same algorithm as the interpreter
222 uses when searching for modules. If the name cannot be matched according to the
223 interpreter's rules, ``None`` is returned.
224
225
226.. function:: ismodule(object)
227
228 Return true if the object is a module.
229
230
231.. function:: isclass(object)
232
233 Return true if the object is a class.
234
235
236.. function:: ismethod(object)
237
238 Return true if the object is a method.
239
240
241.. function:: isfunction(object)
242
Georg Brandl584265b2007-12-02 14:58:50 +0000243 Return true if the object is a Python function or unnamed (:term:`lambda`) function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000244
245
246.. function:: istraceback(object)
247
248 Return true if the object is a traceback.
249
250
251.. function:: isframe(object)
252
253 Return true if the object is a frame.
254
255
256.. function:: iscode(object)
257
258 Return true if the object is a code.
259
260
261.. function:: isbuiltin(object)
262
263 Return true if the object is a built-in function.
264
265
266.. function:: isroutine(object)
267
268 Return true if the object is a user-defined or built-in function or method.
269
270
271.. function:: ismethoddescriptor(object)
272
Georg Brandl5c174bb2007-10-21 10:32:54 +0000273 Return true if the object is a method descriptor, but not if :func:`ismethod`
274 or :func:`isclass` or :func:`isfunction` are true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000275
Georg Brandl5c174bb2007-10-21 10:32:54 +0000276 This is new as of Python 2.2, and, for example, is true of
277 ``int.__add__``. An object passing this test has a :attr:`__get__` attribute
278 but not a :attr:`__set__` attribute, but beyond that the set of attributes
279 varies. :attr:`__name__` is usually sensible, and :attr:`__doc__` often is.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000280
Georg Brandl5c174bb2007-10-21 10:32:54 +0000281 Methods implemented via descriptors that also pass one of the other tests
282 return false from the :func:`ismethoddescriptor` test, simply because the
283 other tests promise more -- you can, e.g., count on having the
284 :attr:`im_func` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000285
286
287.. function:: isdatadescriptor(object)
288
289 Return true if the object is a data descriptor.
290
Georg Brandl5c174bb2007-10-21 10:32:54 +0000291 Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute.
292 Examples are properties (defined in Python), getsets, and members. The
293 latter two are defined in C and there are more specific tests available for
294 those types, which is robust across Python implementations. Typically, data
295 descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes
296 (properties, getsets, and members have both of these attributes), but this is
297 not guaranteed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000298
299 .. versionadded:: 2.3
300
301
302.. function:: isgetsetdescriptor(object)
303
304 Return true if the object is a getset descriptor.
305
306 getsets are attributes defined in extension modules via ``PyGetSetDef``
307 structures. For Python implementations without such types, this method will
308 always return ``False``.
309
310 .. versionadded:: 2.5
311
312
313.. function:: ismemberdescriptor(object)
314
315 Return true if the object is a member descriptor.
316
317 Member descriptors are attributes defined in extension modules via
Georg Brandl5c174bb2007-10-21 10:32:54 +0000318 ``PyMemberDef`` structures. For Python implementations without such types,
319 this method will always return ``False``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000320
321 .. versionadded:: 2.5
322
323
324.. _inspect-source:
325
326Retrieving source code
327----------------------
328
329
330.. function:: getdoc(object)
331
332 Get the documentation string for an object. All tabs are expanded to spaces. To
333 clean up docstrings that are indented to line up with blocks of code, any
334 whitespace than can be uniformly removed from the second line onwards is
335 removed.
336
337
338.. function:: getcomments(object)
339
340 Return in a single string any lines of comments immediately preceding the
341 object's source code (for a class, function, or method), or at the top of the
342 Python source file (if the object is a module).
343
344
345.. function:: getfile(object)
346
347 Return the name of the (text or binary) file in which an object was defined.
348 This will fail with a :exc:`TypeError` if the object is a built-in module,
349 class, or function.
350
351
352.. function:: getmodule(object)
353
354 Try to guess which module an object was defined in.
355
356
357.. function:: getsourcefile(object)
358
359 Return the name of the Python source file in which an object was defined. This
360 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
361 function.
362
363
364.. function:: getsourcelines(object)
365
366 Return a list of source lines and starting line number for an object. The
367 argument may be a module, class, method, function, traceback, frame, or code
368 object. The source code is returned as a list of the lines corresponding to the
369 object and the line number indicates where in the original source file the first
370 line of code was found. An :exc:`IOError` is raised if the source code cannot
371 be retrieved.
372
373
374.. function:: getsource(object)
375
376 Return the text of the source code for an object. The argument may be a module,
377 class, method, function, traceback, frame, or code object. The source code is
378 returned as a single string. An :exc:`IOError` is raised if the source code
379 cannot be retrieved.
380
381
382.. _inspect-classes-functions:
383
384Classes and functions
385---------------------
386
387
388.. function:: getclasstree(classes[, unique])
389
390 Arrange the given list of classes into a hierarchy of nested lists. Where a
391 nested list appears, it contains classes derived from the class whose entry
392 immediately precedes the list. Each entry is a 2-tuple containing a class and a
393 tuple of its base classes. If the *unique* argument is true, exactly one entry
394 appears in the returned structure for each class in the given list. Otherwise,
395 classes using multiple inheritance and their descendants will appear multiple
396 times.
397
398
399.. function:: getargspec(func)
400
401 Get the names and default values of a function's arguments. A tuple of four
402 things is returned: ``(args, varargs, varkw, defaults)``. *args* is a list of
403 the argument names (it may contain nested lists). *varargs* and *varkw* are the
404 names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a tuple of
405 default argument values or None if there are no default arguments; if this tuple
406 has *n* elements, they correspond to the last *n* elements listed in *args*.
407
408
409.. function:: getargvalues(frame)
410
411 Get information about arguments passed into a particular frame. A tuple of four
412 things is returned: ``(args, varargs, varkw, locals)``. *args* is a list of the
413 argument names (it may contain nested lists). *varargs* and *varkw* are the
414 names of the ``*`` and ``**`` arguments or ``None``. *locals* is the locals
415 dictionary of the given frame.
416
417
418.. function:: formatargspec(args[, varargs, varkw, defaults, formatarg, formatvarargs, formatvarkw, formatvalue, join])
419
420 Format a pretty argument spec from the four values returned by
421 :func:`getargspec`. The format\* arguments are the corresponding optional
422 formatting functions that are called to turn names and values into strings.
423
424
425.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue, join])
426
427 Format a pretty argument spec from the four values returned by
428 :func:`getargvalues`. The format\* arguments are the corresponding optional
429 formatting functions that are called to turn names and values into strings.
430
431
432.. function:: getmro(cls)
433
434 Return a tuple of class cls's base classes, including cls, in method resolution
435 order. No class appears more than once in this tuple. Note that the method
436 resolution order depends on cls's type. Unless a very peculiar user-defined
437 metatype is in use, cls will be the first element of the tuple.
438
439
440.. _inspect-stack:
441
442The interpreter stack
443---------------------
444
445When the following functions return "frame records," each record is a tuple of
446six items: the frame object, the filename, the line number of the current line,
447the function name, a list of lines of context from the source code, and the
448index of the current line within that list.
449
450.. warning::
451
452 Keeping references to frame objects, as found in the first element of the frame
453 records these functions return, can cause your program to create reference
454 cycles. Once a reference cycle has been created, the lifespan of all objects
455 which can be accessed from the objects which form the cycle can become much
456 longer even if Python's optional cycle detector is enabled. If such cycles must
457 be created, it is important to ensure they are explicitly broken to avoid the
458 delayed destruction of objects and increased memory consumption which occurs.
459
460 Though the cycle detector will catch these, destruction of the frames (and local
461 variables) can be made deterministic by removing the cycle in a
462 :keyword:`finally` clause. This is also important if the cycle detector was
463 disabled when Python was compiled or using :func:`gc.disable`. For example::
464
465 def handle_stackframe_without_leak():
466 frame = inspect.currentframe()
467 try:
468 # do something with the frame
469 finally:
470 del frame
471
472The optional *context* argument supported by most of these functions specifies
473the number of lines of context to return, which are centered around the current
474line.
475
476
477.. function:: getframeinfo(frame[, context])
478
479 Get information about a frame or traceback object. A 5-tuple is returned, the
480 last five elements of the frame's frame record.
481
482
483.. function:: getouterframes(frame[, context])
484
485 Get a list of frame records for a frame and all outer frames. These frames
486 represent the calls that lead to the creation of *frame*. The first entry in the
487 returned list represents *frame*; the last entry represents the outermost call
488 on *frame*'s stack.
489
490
491.. function:: getinnerframes(traceback[, context])
492
493 Get a list of frame records for a traceback's frame and all inner frames. These
494 frames represent calls made as a consequence of *frame*. The first entry in the
495 list represents *traceback*; the last entry represents where the exception was
496 raised.
497
498
499.. function:: currentframe()
500
501 Return the frame object for the caller's stack frame.
502
503
504.. function:: stack([context])
505
506 Return a list of frame records for the caller's stack. The first entry in the
507 returned list represents the caller; the last entry represents the outermost
508 call on the stack.
509
510
511.. function:: trace([context])
512
513 Return a list of frame records for the stack between the current frame and the
514 frame in which an exception currently being handled was raised in. The first
515 entry in the list represents the caller; the last entry represents where the
516 exception was raised.
517