blob: cc88acfa2151fab2e671f21aac426efefe7e70cd [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`inspect` --- Inspect live objects
2=======================================
3
4.. module:: inspect
5 :synopsis: Extract information and source code from live objects.
6.. moduleauthor:: Ka-Ping Yee <ping@lfw.org>
7.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
8
9
Georg Brandl116aa622007-08-15 14:28:22 +000010The :mod:`inspect` module provides several useful functions to help get
11information about live objects such as modules, classes, methods, functions,
12tracebacks, frame objects, and code objects. For example, it can help you
13examine the contents of a class, retrieve the source code of a method, extract
14and format the argument list for a function, or get all the information you need
15to display a detailed traceback.
16
17There are four main kinds of services provided by this module: type checking,
18getting source code, inspecting classes and functions, and examining the
19interpreter stack.
20
21
22.. _inspect-types:
23
24Types and members
25-----------------
26
27The :func:`getmembers` function retrieves the members of an object such as a
Christian Heimes78644762008-03-04 23:39:23 +000028class or module. The sixteen functions whose names begin with "is" are mainly
Georg Brandl116aa622007-08-15 14:28:22 +000029provided as convenient choices for the second argument to :func:`getmembers`.
30They also help you determine when you can expect to find the following special
31attributes:
32
Georg Brandl55ac8f02007-09-01 13:51:09 +000033+-----------+-----------------+---------------------------+
34| Type | Attribute | Description |
35+===========+=================+===========================+
36| module | __doc__ | documentation string |
37+-----------+-----------------+---------------------------+
38| | __file__ | filename (missing for |
39| | | built-in modules) |
40+-----------+-----------------+---------------------------+
41| class | __doc__ | documentation string |
42+-----------+-----------------+---------------------------+
43| | __module__ | name of module in which |
44| | | this class was defined |
45+-----------+-----------------+---------------------------+
46| method | __doc__ | documentation string |
47+-----------+-----------------+---------------------------+
48| | __name__ | name with which this |
49| | | method was defined |
50+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000051| | __func__ | function object |
Georg Brandl55ac8f02007-09-01 13:51:09 +000052| | | containing implementation |
53| | | of method |
54+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000055| | __self__ | instance to which this |
Georg Brandl55ac8f02007-09-01 13:51:09 +000056| | | method is bound, or |
57| | | ``None`` |
58+-----------+-----------------+---------------------------+
59| function | __doc__ | documentation string |
60+-----------+-----------------+---------------------------+
61| | __name__ | name with which this |
62| | | function was defined |
63+-----------+-----------------+---------------------------+
64| | __code__ | code object containing |
65| | | compiled function |
Georg Brandl9afde1c2007-11-01 20:32:30 +000066| | | :term:`bytecode` |
Georg Brandl55ac8f02007-09-01 13:51:09 +000067+-----------+-----------------+---------------------------+
68| | __defaults__ | tuple of any default |
69| | | values for arguments |
70+-----------+-----------------+---------------------------+
71| | __globals__ | global namespace in which |
72| | | this function was defined |
73+-----------+-----------------+---------------------------+
74| traceback | tb_frame | frame object at this |
75| | | level |
76+-----------+-----------------+---------------------------+
77| | tb_lasti | index of last attempted |
78| | | instruction in bytecode |
79+-----------+-----------------+---------------------------+
80| | tb_lineno | current line number in |
81| | | Python source code |
82+-----------+-----------------+---------------------------+
83| | tb_next | next inner traceback |
84| | | object (called by this |
85| | | level) |
86+-----------+-----------------+---------------------------+
87| frame | f_back | next outer frame object |
88| | | (this frame's caller) |
89+-----------+-----------------+---------------------------+
90| | f_builtins | built-in namespace seen |
91| | | by this frame |
92+-----------+-----------------+---------------------------+
93| | f_code | code object being |
94| | | executed in this frame |
95+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +000096| | f_globals | global namespace seen by |
97| | | this frame |
98+-----------+-----------------+---------------------------+
99| | f_lasti | index of last attempted |
100| | | instruction in bytecode |
101+-----------+-----------------+---------------------------+
102| | f_lineno | current line number in |
103| | | Python source code |
104+-----------+-----------------+---------------------------+
105| | f_locals | local namespace seen by |
106| | | this frame |
107+-----------+-----------------+---------------------------+
108| | f_restricted | 0 or 1 if frame is in |
109| | | restricted execution mode |
110+-----------+-----------------+---------------------------+
111| | f_trace | tracing function for this |
112| | | frame, or ``None`` |
113+-----------+-----------------+---------------------------+
114| code | co_argcount | number of arguments (not |
115| | | including \* or \*\* |
116| | | args) |
117+-----------+-----------------+---------------------------+
118| | co_code | string of raw compiled |
119| | | bytecode |
120+-----------+-----------------+---------------------------+
121| | co_consts | tuple of constants used |
122| | | in the bytecode |
123+-----------+-----------------+---------------------------+
124| | co_filename | name of file in which |
125| | | this code object was |
126| | | created |
127+-----------+-----------------+---------------------------+
128| | co_firstlineno | number of first line in |
129| | | Python source code |
130+-----------+-----------------+---------------------------+
131| | co_flags | bitmap: 1=optimized ``|`` |
132| | | 2=newlocals ``|`` 4=\*arg |
133| | | ``|`` 8=\*\*arg |
134+-----------+-----------------+---------------------------+
135| | co_lnotab | encoded mapping of line |
136| | | numbers to bytecode |
137| | | indices |
138+-----------+-----------------+---------------------------+
139| | co_name | name with which this code |
140| | | object was defined |
141+-----------+-----------------+---------------------------+
142| | co_names | tuple of names of local |
143| | | variables |
144+-----------+-----------------+---------------------------+
145| | co_nlocals | number of local variables |
146+-----------+-----------------+---------------------------+
147| | co_stacksize | virtual machine stack |
148| | | space required |
149+-----------+-----------------+---------------------------+
150| | co_varnames | tuple of names of |
151| | | arguments and local |
152| | | variables |
153+-----------+-----------------+---------------------------+
154| builtin | __doc__ | documentation string |
155+-----------+-----------------+---------------------------+
156| | __name__ | original name of this |
157| | | function or method |
158+-----------+-----------------+---------------------------+
159| | __self__ | instance to which a |
160| | | method is bound, or |
161| | | ``None`` |
162+-----------+-----------------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000163
164
165.. function:: getmembers(object[, predicate])
166
167 Return all the members of an object in a list of (name, value) pairs sorted by
168 name. If the optional *predicate* argument is supplied, only members for which
169 the predicate returns a true value are included.
170
Christian Heimes7f044312008-01-06 17:05:40 +0000171 .. note::
172
173 :func:`getmembers` does not return metaclass attributes when the argument
174 is a class (this behavior is inherited from the :func:`dir` function).
175
Georg Brandl116aa622007-08-15 14:28:22 +0000176
177.. function:: getmoduleinfo(path)
178
Christian Heimes25bb7832008-01-11 16:17:00 +0000179 Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode,
180 module_type)`` of values that describe how Python will interpret the file
Georg Brandl116aa622007-08-15 14:28:22 +0000181 identified by *path* if it is a module, or ``None`` if it would not be
182 identified as a module. The return tuple is ``(name, suffix, mode, mtype)``,
183 where *name* is the name of the module without the name of any enclosing
184 package, *suffix* is the trailing part of the file name (which may not be a
185 dot-delimited extension), *mode* is the :func:`open` mode that would be used
186 (``'r'`` or ``'rb'``), and *mtype* is an integer giving the type of the
187 module. *mtype* will have a value which can be compared to the constants
188 defined in the :mod:`imp` module; see the documentation for that module for
189 more information on module types.
190
191
192.. function:: getmodulename(path)
193
194 Return the name of the module named by the file *path*, without including the
195 names of enclosing packages. This uses the same algorithm as the interpreter
196 uses when searching for modules. If the name cannot be matched according to the
197 interpreter's rules, ``None`` is returned.
198
199
200.. function:: ismodule(object)
201
202 Return true if the object is a module.
203
204
205.. function:: isclass(object)
206
207 Return true if the object is a class.
208
209
210.. function:: ismethod(object)
211
212 Return true if the object is a method.
213
214
215.. function:: isfunction(object)
216
Georg Brandl3dd33882009-06-01 17:35:27 +0000217 Return true if the object is a Python function or unnamed (:term:`lambda`)
218 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
Georg Brandl495f7b52009-10-27 15:28:25 +0000293 .. impl-detail::
294
295 getsets are attributes defined in extension modules via
296 :ctype:`PyGetSetDef` structures. For Python implementations without such
297 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000298
Georg Brandl116aa622007-08-15 14:28:22 +0000299
300.. function:: ismemberdescriptor(object)
301
302 Return true if the object is a member descriptor.
303
Georg Brandl495f7b52009-10-27 15:28:25 +0000304 .. impl-detail::
305
306 Member descriptors are attributes defined in extension modules via
307 :ctype:`PyMemberDef` structures. For Python implementations without such
308 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000309
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311.. _inspect-source:
312
313Retrieving source code
314----------------------
315
Georg Brandl116aa622007-08-15 14:28:22 +0000316.. function:: getdoc(object)
317
Georg Brandl0c77a822008-06-10 16:37:50 +0000318 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Georg Brandl116aa622007-08-15 14:28:22 +0000319
320
321.. function:: getcomments(object)
322
323 Return in a single string any lines of comments immediately preceding the
324 object's source code (for a class, function, or method), or at the top of the
325 Python source file (if the object is a module).
326
327
328.. function:: getfile(object)
329
330 Return the name of the (text or binary) file in which an object was defined.
331 This will fail with a :exc:`TypeError` if the object is a built-in module,
332 class, or function.
333
334
335.. function:: getmodule(object)
336
337 Try to guess which module an object was defined in.
338
339
340.. function:: getsourcefile(object)
341
342 Return the name of the Python source file in which an object was defined. This
343 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
344 function.
345
346
347.. function:: getsourcelines(object)
348
349 Return a list of source lines and starting line number for an object. The
350 argument may be a module, class, method, function, traceback, frame, or code
351 object. The source code is returned as a list of the lines corresponding to the
352 object and the line number indicates where in the original source file the first
353 line of code was found. An :exc:`IOError` is raised if the source code cannot
354 be retrieved.
355
356
357.. function:: getsource(object)
358
359 Return the text of the source code for an object. The argument may be a module,
360 class, method, function, traceback, frame, or code object. The source code is
361 returned as a single string. An :exc:`IOError` is raised if the source code
362 cannot be retrieved.
363
364
Georg Brandl0c77a822008-06-10 16:37:50 +0000365.. function:: cleandoc(doc)
366
367 Clean up indentation from docstrings that are indented to line up with blocks
368 of code. Any whitespace that can be uniformly removed from the second line
369 onwards is removed. Also, all tabs are expanded to spaces.
370
Georg Brandl0c77a822008-06-10 16:37:50 +0000371
Georg Brandl116aa622007-08-15 14:28:22 +0000372.. _inspect-classes-functions:
373
374Classes and functions
375---------------------
376
Georg Brandl3dd33882009-06-01 17:35:27 +0000377.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000378
379 Arrange the given list of classes into a hierarchy of nested lists. Where a
380 nested list appears, it contains classes derived from the class whose entry
381 immediately precedes the list. Each entry is a 2-tuple containing a class and a
382 tuple of its base classes. If the *unique* argument is true, exactly one entry
383 appears in the returned structure for each class in the given list. Otherwise,
384 classes using multiple inheritance and their descendants will appear multiple
385 times.
386
387
388.. function:: getargspec(func)
389
Georg Brandl82402752010-01-09 09:48:46 +0000390 Get the names and default values of a Python function's arguments. A
Christian Heimes25bb7832008-01-11 16:17:00 +0000391 :term:`named tuple` ``ArgSpec(args, varargs, keywords,
392 defaults)`` is returned. *args* is a list of
Georg Brandl138bcb52007-09-12 19:04:21 +0000393 the argument names. *varargs* and *varkw* are the names of the ``*`` and
394 ``**`` arguments or ``None``. *defaults* is a tuple of default argument
395 values or None if there are no default arguments; if this tuple has *n*
396 elements, they correspond to the last *n* elements listed in *args*.
397
398 .. deprecated:: 3.0
399 Use :func:`getfullargspec` instead, which provides information about
Benjamin Peterson3e8e9cc2008-11-12 21:26:46 +0000400 keyword-only arguments and annotations.
Georg Brandl138bcb52007-09-12 19:04:21 +0000401
402
403.. function:: getfullargspec(func)
404
Georg Brandl82402752010-01-09 09:48:46 +0000405 Get the names and default values of a Python function's arguments. A
406 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000407
Georg Brandl3dd33882009-06-01 17:35:27 +0000408 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
409 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000410
411 *args* is a list of the argument names. *varargs* and *varkw* are the names
412 of the ``*`` and ``**`` arguments or ``None``. *defaults* is an n-tuple of
413 the default values of the last n arguments. *kwonlyargs* is a list of
414 keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
415 from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
416 names to annotations.
417
418 The first four items in the tuple correspond to :func:`getargspec`.
Georg Brandl116aa622007-08-15 14:28:22 +0000419
420
421.. function:: getargvalues(frame)
422
Georg Brandl3dd33882009-06-01 17:35:27 +0000423 Get information about arguments passed into a particular frame. A
424 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
425 returned. *args* is a list of the argument names (it may contain nested
426 lists). *varargs* and *varkw* are the names of the ``*`` and ``**`` arguments
427 or ``None``. *locals* is the locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000428
429
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
Georg Brandle720c0a2009-04-27 16:20:50 +0000462.. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000463
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
Georg Brandl3dd33882009-06-01 17:35:27 +0000489.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000490
Georg Brandl48310cd2009-01-03 21:18:54 +0000491 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +0000492 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000493
494
Georg Brandl3dd33882009-06-01 17:35:27 +0000495.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000496
497 Get a list of frame records for a frame and all outer frames. These frames
498 represent the calls that lead to the creation of *frame*. The first entry in the
499 returned list represents *frame*; the last entry represents the outermost call
500 on *frame*'s stack.
501
502
Georg Brandl3dd33882009-06-01 17:35:27 +0000503.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000504
505 Get a list of frame records for a traceback's frame and all inner frames. These
506 frames represent calls made as a consequence of *frame*. The first entry in the
507 list represents *traceback*; the last entry represents where the exception was
508 raised.
509
510
511.. function:: currentframe()
512
513 Return the frame object for the caller's stack frame.
514
Georg Brandl495f7b52009-10-27 15:28:25 +0000515 .. impl-detail::
516
517 This function relies on Python stack frame support in the interpreter,
518 which isn't guaranteed to exist in all implementations of Python. If
519 running in an implementation without Python stack frame support this
520 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000521
Georg Brandl116aa622007-08-15 14:28:22 +0000522
Georg Brandl3dd33882009-06-01 17:35:27 +0000523.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000524
525 Return a list of frame records for the caller's stack. The first entry in the
526 returned list represents the caller; the last entry represents the outermost
527 call on the stack.
528
529
Georg Brandl3dd33882009-06-01 17:35:27 +0000530.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000531
532 Return a list of frame records for the stack between the current frame and the
533 frame in which an exception currently being handled was raised in. The first
534 entry in the list represents the caller; the last entry represents where the
535 exception was raised.
536