blob: e290d735bf14d8a1f2d0a8fd344f1bd2723bba14 [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+-----------+-----------------+---------------------------+
Georg Brandlc4a55fc2010-02-06 18:46:57 +000090| | f_builtins | builtins namespace seen |
Georg Brandl55ac8f02007-09-01 13:51:09 +000091| | | 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
Georg Brandlb30f3302011-01-06 09:23:56 +0000179 Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode, module_type)``
180 of values that describe how Python will interpret the file identified by
181 *path* if it is a module, or ``None`` if it would not be identified as a
182 module. In that tuple, *name* is the name of the module without the name of
183 any enclosing package, *suffix* is the trailing part of the file name (which
184 may not be a dot-delimited extension), *mode* is the :func:`open` mode that
185 would be used (``'r'`` or ``'rb'``), and *module_type* is an integer giving
186 the type of the module. *module_type* will have a value which can be
187 compared to the constants defined in the :mod:`imp` module; see the
188 documentation for that module for more information on module types.
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190
191.. function:: getmodulename(path)
192
193 Return the name of the module named by the file *path*, without including the
194 names of enclosing packages. This uses the same algorithm as the interpreter
195 uses when searching for modules. If the name cannot be matched according to the
196 interpreter's rules, ``None`` is returned.
197
198
199.. function:: ismodule(object)
200
201 Return true if the object is a module.
202
203
204.. function:: isclass(object)
205
Georg Brandl39cadc32010-10-15 16:53:24 +0000206 Return true if the object is a class, whether built-in or created in Python
207 code.
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209
210.. function:: ismethod(object)
211
Georg Brandl39cadc32010-10-15 16:53:24 +0000212 Return true if the object is a bound method written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214
215.. function:: isfunction(object)
216
Georg Brandl39cadc32010-10-15 16:53:24 +0000217 Return true if the object is a Python function, which includes functions
218 created by a :term:`lambda` expression.
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
Georg Brandl39cadc32010-10-15 16:53:24 +0000248 Return true if the object is a built-in function or a bound built-in method.
Georg Brandl116aa622007-08-15 14:28:22 +0000249
250
251.. function:: isroutine(object)
252
253 Return true if the object is a user-defined or built-in function or method.
254
Georg Brandl39cadc32010-10-15 16:53:24 +0000255
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000256.. function:: isabstract(object)
257
258 Return true if the object is an abstract base class.
259
Georg Brandl116aa622007-08-15 14:28:22 +0000260
261.. function:: ismethoddescriptor(object)
262
Georg Brandl39cadc32010-10-15 16:53:24 +0000263 Return true if the object is a method descriptor, but not if
264 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
265 are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000266
Georg Brandle6bcc912008-05-12 18:05:20 +0000267 This, for example, is true of ``int.__add__``. An object passing this test
268 has a :attr:`__get__` attribute but not a :attr:`__set__` attribute, but
269 beyond that the set of attributes varies. :attr:`__name__` is usually
270 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000271
Georg Brandl9afde1c2007-11-01 20:32:30 +0000272 Methods implemented via descriptors that also pass one of the other tests
273 return false from the :func:`ismethoddescriptor` test, simply because the
274 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000275 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000276
277
278.. function:: isdatadescriptor(object)
279
280 Return true if the object is a data descriptor.
281
Georg Brandl9afde1c2007-11-01 20:32:30 +0000282 Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute.
283 Examples are properties (defined in Python), getsets, and members. The
284 latter two are defined in C and there are more specific tests available for
285 those types, which is robust across Python implementations. Typically, data
286 descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes
287 (properties, getsets, and members have both of these attributes), but this is
288 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000289
Georg Brandl116aa622007-08-15 14:28:22 +0000290
291.. function:: isgetsetdescriptor(object)
292
293 Return true if the object is a getset descriptor.
294
Georg Brandl495f7b52009-10-27 15:28:25 +0000295 .. impl-detail::
296
297 getsets are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000298 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000299 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000300
Georg Brandl116aa622007-08-15 14:28:22 +0000301
302.. function:: ismemberdescriptor(object)
303
304 Return true if the object is a member descriptor.
305
Georg Brandl495f7b52009-10-27 15:28:25 +0000306 .. impl-detail::
307
308 Member descriptors are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000309 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000310 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000311
Georg Brandl116aa622007-08-15 14:28:22 +0000312
313.. _inspect-source:
314
315Retrieving source code
316----------------------
317
Georg Brandl116aa622007-08-15 14:28:22 +0000318.. function:: getdoc(object)
319
Georg Brandl0c77a822008-06-10 16:37:50 +0000320 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Georg Brandl116aa622007-08-15 14:28:22 +0000321
322
323.. function:: getcomments(object)
324
325 Return in a single string any lines of comments immediately preceding the
326 object's source code (for a class, function, or method), or at the top of the
327 Python source file (if the object is a module).
328
329
330.. function:: getfile(object)
331
332 Return the name of the (text or binary) file in which an object was defined.
333 This will fail with a :exc:`TypeError` if the object is a built-in module,
334 class, or function.
335
336
337.. function:: getmodule(object)
338
339 Try to guess which module an object was defined in.
340
341
342.. function:: getsourcefile(object)
343
344 Return the name of the Python source file in which an object was defined. This
345 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
346 function.
347
348
349.. function:: getsourcelines(object)
350
351 Return a list of source lines and starting line number for an object. The
352 argument may be a module, class, method, function, traceback, frame, or code
353 object. The source code is returned as a list of the lines corresponding to the
354 object and the line number indicates where in the original source file the first
355 line of code was found. An :exc:`IOError` is raised if the source code cannot
356 be retrieved.
357
358
359.. function:: getsource(object)
360
361 Return the text of the source code for an object. The argument may be a module,
362 class, method, function, traceback, frame, or code object. The source code is
363 returned as a single string. An :exc:`IOError` is raised if the source code
364 cannot be retrieved.
365
366
Georg Brandl0c77a822008-06-10 16:37:50 +0000367.. function:: cleandoc(doc)
368
369 Clean up indentation from docstrings that are indented to line up with blocks
370 of code. Any whitespace that can be uniformly removed from the second line
371 onwards is removed. Also, all tabs are expanded to spaces.
372
Georg Brandl0c77a822008-06-10 16:37:50 +0000373
Georg Brandl116aa622007-08-15 14:28:22 +0000374.. _inspect-classes-functions:
375
376Classes and functions
377---------------------
378
Georg Brandl3dd33882009-06-01 17:35:27 +0000379.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000380
381 Arrange the given list of classes into a hierarchy of nested lists. Where a
382 nested list appears, it contains classes derived from the class whose entry
383 immediately precedes the list. Each entry is a 2-tuple containing a class and a
384 tuple of its base classes. If the *unique* argument is true, exactly one entry
385 appears in the returned structure for each class in the given list. Otherwise,
386 classes using multiple inheritance and their descendants will appear multiple
387 times.
388
389
390.. function:: getargspec(func)
391
Georg Brandl82402752010-01-09 09:48:46 +0000392 Get the names and default values of a Python function's arguments. A
Georg Brandlb30f3302011-01-06 09:23:56 +0000393 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
394 returned. *args* is a list of the argument names. *varargs* and *keywords*
395 are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a
396 tuple of default argument values or None if there are no default arguments;
397 if this tuple has *n* elements, they correspond to the last *n* elements
398 listed in *args*.
Georg Brandl138bcb52007-09-12 19:04:21 +0000399
400 .. deprecated:: 3.0
401 Use :func:`getfullargspec` instead, which provides information about
Benjamin Peterson3e8e9cc2008-11-12 21:26:46 +0000402 keyword-only arguments and annotations.
Georg Brandl138bcb52007-09-12 19:04:21 +0000403
404
405.. function:: getfullargspec(func)
406
Georg Brandl82402752010-01-09 09:48:46 +0000407 Get the names and default values of a Python function's arguments. A
408 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000409
Georg Brandl3dd33882009-06-01 17:35:27 +0000410 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
411 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000412
413 *args* is a list of the argument names. *varargs* and *varkw* are the names
414 of the ``*`` and ``**`` arguments or ``None``. *defaults* is an n-tuple of
415 the default values of the last n arguments. *kwonlyargs* is a list of
416 keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
417 from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
418 names to annotations.
419
420 The first four items in the tuple correspond to :func:`getargspec`.
Georg Brandl116aa622007-08-15 14:28:22 +0000421
422
423.. function:: getargvalues(frame)
424
Georg Brandl3dd33882009-06-01 17:35:27 +0000425 Get information about arguments passed into a particular frame. A
426 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000427 returned. *args* is a list of the argument names. *varargs* and *keywords*
428 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000429 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000430
431
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000432.. function:: formatargspec(args[, varargs, varkw, defaults, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000433
434 Format a pretty argument spec from the four values returned by
435 :func:`getargspec`. The format\* arguments are the corresponding optional
436 formatting functions that are called to turn names and values into strings.
437
438
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000439.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000440
441 Format a pretty argument spec from the four values returned by
442 :func:`getargvalues`. The format\* arguments are the corresponding optional
443 formatting functions that are called to turn names and values into strings.
444
445
446.. function:: getmro(cls)
447
448 Return a tuple of class cls's base classes, including cls, in method resolution
449 order. No class appears more than once in this tuple. Note that the method
450 resolution order depends on cls's type. Unless a very peculiar user-defined
451 metatype is in use, cls will be the first element of the tuple.
452
453
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000454.. function:: getcallargs(func[, *args][, **kwds])
455
456 Bind the *args* and *kwds* to the argument names of the Python function or
457 method *func*, as if it was called with them. For bound methods, bind also the
458 first argument (typically named ``self``) to the associated instance. A dict
459 is returned, mapping the argument names (including the names of the ``*`` and
460 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
461 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
462 an exception because of incompatible signature, an exception of the same type
463 and the same or similar message is raised. For example::
464
465 >>> from inspect import getcallargs
466 >>> def f(a, b=1, *pos, **named):
467 ... pass
468 >>> getcallargs(f, 1, 2, 3)
469 {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
470 >>> getcallargs(f, a=2, x=4)
471 {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
472 >>> getcallargs(f)
473 Traceback (most recent call last):
474 ...
475 TypeError: f() takes at least 1 argument (0 given)
476
477 .. versionadded:: 3.2
478
479
Georg Brandl116aa622007-08-15 14:28:22 +0000480.. _inspect-stack:
481
482The interpreter stack
483---------------------
484
485When the following functions return "frame records," each record is a tuple of
486six items: the frame object, the filename, the line number of the current line,
487the function name, a list of lines of context from the source code, and the
488index of the current line within that list.
489
Georg Brandle720c0a2009-04-27 16:20:50 +0000490.. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000491
492 Keeping references to frame objects, as found in the first element of the frame
493 records these functions return, can cause your program to create reference
494 cycles. Once a reference cycle has been created, the lifespan of all objects
495 which can be accessed from the objects which form the cycle can become much
496 longer even if Python's optional cycle detector is enabled. If such cycles must
497 be created, it is important to ensure they are explicitly broken to avoid the
498 delayed destruction of objects and increased memory consumption which occurs.
499
500 Though the cycle detector will catch these, destruction of the frames (and local
501 variables) can be made deterministic by removing the cycle in a
502 :keyword:`finally` clause. This is also important if the cycle detector was
503 disabled when Python was compiled or using :func:`gc.disable`. For example::
504
505 def handle_stackframe_without_leak():
506 frame = inspect.currentframe()
507 try:
508 # do something with the frame
509 finally:
510 del frame
511
512The optional *context* argument supported by most of these functions specifies
513the number of lines of context to return, which are centered around the current
514line.
515
516
Georg Brandl3dd33882009-06-01 17:35:27 +0000517.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000518
Georg Brandl48310cd2009-01-03 21:18:54 +0000519 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +0000520 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000521
522
Georg Brandl3dd33882009-06-01 17:35:27 +0000523.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000524
525 Get a list of frame records for a frame and all outer frames. These frames
526 represent the calls that lead to the creation of *frame*. The first entry in the
527 returned list represents *frame*; the last entry represents the outermost call
528 on *frame*'s stack.
529
530
Georg Brandl3dd33882009-06-01 17:35:27 +0000531.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000532
533 Get a list of frame records for a traceback's frame and all inner frames. These
534 frames represent calls made as a consequence of *frame*. The first entry in the
535 list represents *traceback*; the last entry represents where the exception was
536 raised.
537
538
539.. function:: currentframe()
540
541 Return the frame object for the caller's stack frame.
542
Georg Brandl495f7b52009-10-27 15:28:25 +0000543 .. impl-detail::
544
545 This function relies on Python stack frame support in the interpreter,
546 which isn't guaranteed to exist in all implementations of Python. If
547 running in an implementation without Python stack frame support this
548 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000549
Georg Brandl116aa622007-08-15 14:28:22 +0000550
Georg Brandl3dd33882009-06-01 17:35:27 +0000551.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000552
553 Return a list of frame records for the caller's stack. The first entry in the
554 returned list represents the caller; the last entry represents the outermost
555 call on the stack.
556
557
Georg Brandl3dd33882009-06-01 17:35:27 +0000558.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000559
560 Return a list of frame records for the stack between the current frame and the
561 frame in which an exception currently being handled was raised in. The first
562 entry in the list represents the caller; the last entry represents where the
563 exception was raised.
564
Michael Foord95fc51d2010-11-20 15:07:30 +0000565
566Fetching attributes statically
567------------------------------
568
569Both :func:`getattr` and :func:`hasattr` can trigger code execution when
570fetching or checking for the existence of attributes. Descriptors, like
571properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
572may be called.
573
574For cases where you want passive introspection, like documentation tools, this
575can be inconvenient. `getattr_static` has the same signature as :func:`getattr`
576but avoids executing code when it fetches attributes.
577
578.. function:: getattr_static(obj, attr, default=None)
579
580 Retrieve attributes without triggering dynamic lookup via the
581 descriptor protocol, `__getattr__` or `__getattribute__`.
582
583 Note: this function may not be able to retrieve all attributes
584 that getattr can fetch (like dynamically created attributes)
585 and may find attributes that getattr can't (like descriptors
586 that raise AttributeError). It can also return descriptors objects
587 instead of instance members.
588
Nick Coghlan2dad5ca2010-11-21 03:55:53 +0000589 .. versionadded:: 3.2
590
Michael Foorde5162652010-11-20 16:40:44 +0000591The only known case that can cause `getattr_static` to trigger code execution,
592and cause it to return incorrect results (or even break), is where a class uses
593:data:`~object.__slots__` and provides a `__dict__` member using a property or
594descriptor. If you find other cases please report them so they can be fixed
595or documented.
Michael Foord95fc51d2010-11-20 15:07:30 +0000596
Michael Foorde5162652010-11-20 16:40:44 +0000597`getattr_static` does not resolve descriptors, for example slot descriptors or
598getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +0000599is returned instead of the underlying attribute.
600
601You can handle these with code like the following. Note that
602for arbitrary getset descriptors invoking these may trigger
603code execution::
604
605 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +0000606 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +0000607 __slots__ = ['foo']
608
609 slot_descriptor = type(_foo.foo)
610 getset_descriptor = type(type(open(__file__)).name)
611 wrapper_descriptor = type(str.__dict__['__add__'])
612 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
613
614 result = getattr_static(some_object, 'foo')
615 if type(result) in descriptor_types:
616 try:
617 result = result.__get__()
618 except AttributeError:
619 # descriptors can raise AttributeError to
620 # indicate there is no underlying value
621 # in which case the descriptor itself will
622 # have to do
623 pass
Nick Coghlane0f04652010-11-21 03:44:04 +0000624
Nick Coghlan2dad5ca2010-11-21 03:55:53 +0000625
Nick Coghlane0f04652010-11-21 03:44:04 +0000626Current State of a Generator
627----------------------------
628
629When implementing coroutine schedulers and for other advanced uses of
630generators, it is useful to determine whether a generator is currently
631executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +0000632terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +0000633generator to be determined easily.
634
635.. function:: getgeneratorstate(generator)
636
Raymond Hettinger48f3bd32010-12-16 00:30:53 +0000637 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +0000638
Raymond Hettinger48f3bd32010-12-16 00:30:53 +0000639 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +0000640 * GEN_CREATED: Waiting to start execution.
641 * GEN_RUNNING: Currently being executed by the interpreter.
642 * GEN_SUSPENDED: Currently suspended at a yield expression.
643 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +0000644
Nick Coghlan2dad5ca2010-11-21 03:55:53 +0000645 .. versionadded:: 3.2