blob: 57eb4fff82ab4ebe8c69c884749682d3be51dbb5 [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
Raymond Hettinger469271d2011-01-27 20:38:46 +00009**Source code:** :source:`Lib/inspect.py`
10
11--------------
Georg Brandl116aa622007-08-15 14:28:22 +000012
Georg Brandl116aa622007-08-15 14:28:22 +000013The :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
Christian Heimes78644762008-03-04 23:39:23 +000031class or module. The sixteen functions whose names begin with "is" are mainly
Georg Brandl116aa622007-08-15 14:28:22 +000032provided 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
Georg Brandl55ac8f02007-09-01 13:51:09 +000036+-----------+-----------------+---------------------------+
37| Type | Attribute | Description |
38+===========+=================+===========================+
39| module | __doc__ | documentation string |
40+-----------+-----------------+---------------------------+
41| | __file__ | filename (missing for |
42| | | built-in modules) |
43+-----------+-----------------+---------------------------+
44| class | __doc__ | documentation string |
45+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -040046| | __name__ | name with which this |
47| | | class was defined |
48+-----------+-----------------+---------------------------+
49| | __qualname__ | qualified name |
50+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +000051| | __module__ | name of module in which |
52| | | this class was defined |
53+-----------+-----------------+---------------------------+
54| method | __doc__ | documentation string |
55+-----------+-----------------+---------------------------+
56| | __name__ | name with which this |
57| | | method was defined |
58+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -040059| | __qualname__ | qualified name |
60+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000061| | __func__ | function object |
Georg Brandl55ac8f02007-09-01 13:51:09 +000062| | | containing implementation |
63| | | of method |
64+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000065| | __self__ | instance to which this |
Georg Brandl55ac8f02007-09-01 13:51:09 +000066| | | method is bound, or |
67| | | ``None`` |
68+-----------+-----------------+---------------------------+
69| function | __doc__ | documentation string |
70+-----------+-----------------+---------------------------+
71| | __name__ | name with which this |
72| | | function was defined |
73+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -040074| | __qualname__ | qualified name |
75+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +000076| | __code__ | code object containing |
77| | | compiled function |
Georg Brandl9afde1c2007-11-01 20:32:30 +000078| | | :term:`bytecode` |
Georg Brandl55ac8f02007-09-01 13:51:09 +000079+-----------+-----------------+---------------------------+
80| | __defaults__ | tuple of any default |
Yury Selivanovea2d66e2014-01-27 14:26:28 -050081| | | values for positional or |
82| | | keyword parameters |
83+-----------+-----------------+---------------------------+
84| | __kwdefaults__ | mapping of any default |
85| | | values for keyword-only |
86| | | parameters |
Georg Brandl55ac8f02007-09-01 13:51:09 +000087+-----------+-----------------+---------------------------+
88| | __globals__ | global namespace in which |
89| | | this function was defined |
90+-----------+-----------------+---------------------------+
91| traceback | tb_frame | frame object at this |
92| | | level |
93+-----------+-----------------+---------------------------+
94| | tb_lasti | index of last attempted |
95| | | instruction in bytecode |
96+-----------+-----------------+---------------------------+
97| | tb_lineno | current line number in |
98| | | Python source code |
99+-----------+-----------------+---------------------------+
100| | tb_next | next inner traceback |
101| | | object (called by this |
102| | | level) |
103+-----------+-----------------+---------------------------+
104| frame | f_back | next outer frame object |
105| | | (this frame's caller) |
106+-----------+-----------------+---------------------------+
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000107| | f_builtins | builtins namespace seen |
Georg Brandl55ac8f02007-09-01 13:51:09 +0000108| | | by this frame |
109+-----------+-----------------+---------------------------+
110| | f_code | code object being |
111| | | executed in this frame |
112+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000113| | f_globals | global namespace seen by |
114| | | this frame |
115+-----------+-----------------+---------------------------+
116| | f_lasti | index of last attempted |
117| | | instruction in bytecode |
118+-----------+-----------------+---------------------------+
119| | f_lineno | current line number in |
120| | | Python source code |
121+-----------+-----------------+---------------------------+
122| | f_locals | local namespace seen by |
123| | | this frame |
124+-----------+-----------------+---------------------------+
125| | f_restricted | 0 or 1 if frame is in |
126| | | restricted execution mode |
127+-----------+-----------------+---------------------------+
128| | f_trace | tracing function for this |
129| | | frame, or ``None`` |
130+-----------+-----------------+---------------------------+
131| code | co_argcount | number of arguments (not |
132| | | including \* or \*\* |
133| | | args) |
134+-----------+-----------------+---------------------------+
135| | co_code | string of raw compiled |
136| | | bytecode |
137+-----------+-----------------+---------------------------+
138| | co_consts | tuple of constants used |
139| | | in the bytecode |
140+-----------+-----------------+---------------------------+
141| | co_filename | name of file in which |
142| | | this code object was |
143| | | created |
144+-----------+-----------------+---------------------------+
145| | co_firstlineno | number of first line in |
146| | | Python source code |
147+-----------+-----------------+---------------------------+
148| | co_flags | bitmap: 1=optimized ``|`` |
149| | | 2=newlocals ``|`` 4=\*arg |
150| | | ``|`` 8=\*\*arg |
151+-----------+-----------------+---------------------------+
152| | co_lnotab | encoded mapping of line |
153| | | numbers to bytecode |
154| | | indices |
155+-----------+-----------------+---------------------------+
156| | co_name | name with which this code |
157| | | object was defined |
158+-----------+-----------------+---------------------------+
159| | co_names | tuple of names of local |
160| | | variables |
161+-----------+-----------------+---------------------------+
162| | co_nlocals | number of local variables |
163+-----------+-----------------+---------------------------+
164| | co_stacksize | virtual machine stack |
165| | | space required |
166+-----------+-----------------+---------------------------+
167| | co_varnames | tuple of names of |
168| | | arguments and local |
169| | | variables |
170+-----------+-----------------+---------------------------+
171| builtin | __doc__ | documentation string |
172+-----------+-----------------+---------------------------+
173| | __name__ | original name of this |
174| | | function or method |
175+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -0400176| | __qualname__ | qualified name |
177+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000178| | __self__ | instance to which a |
179| | | method is bound, or |
180| | | ``None`` |
181+-----------+-----------------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183
184.. function:: getmembers(object[, predicate])
185
186 Return all the members of an object in a list of (name, value) pairs sorted by
187 name. If the optional *predicate* argument is supplied, only members for which
188 the predicate returns a true value are included.
189
Christian Heimes7f044312008-01-06 17:05:40 +0000190 .. note::
191
Ethan Furman63c141c2013-10-18 00:27:39 -0700192 :func:`getmembers` will only return class attributes defined in the
193 metaclass when the argument is a class and those attributes have been
194 listed in the metaclass' custom :meth:`__dir__`.
Christian Heimes7f044312008-01-06 17:05:40 +0000195
Georg Brandl116aa622007-08-15 14:28:22 +0000196
197.. function:: getmoduleinfo(path)
198
Georg Brandlb30f3302011-01-06 09:23:56 +0000199 Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode, module_type)``
200 of values that describe how Python will interpret the file identified by
201 *path* if it is a module, or ``None`` if it would not be identified as a
202 module. In that tuple, *name* is the name of the module without the name of
203 any enclosing package, *suffix* is the trailing part of the file name (which
204 may not be a dot-delimited extension), *mode* is the :func:`open` mode that
205 would be used (``'r'`` or ``'rb'``), and *module_type* is an integer giving
206 the type of the module. *module_type* will have a value which can be
207 compared to the constants defined in the :mod:`imp` module; see the
208 documentation for that module for more information on module types.
Georg Brandl116aa622007-08-15 14:28:22 +0000209
Brett Cannoncb66eb02012-05-11 12:58:42 -0400210 .. deprecated:: 3.3
211 You may check the file path's suffix against the supported suffixes
212 listed in :mod:`importlib.machinery` to infer the same information.
213
Georg Brandl116aa622007-08-15 14:28:22 +0000214
215.. function:: getmodulename(path)
216
217 Return the name of the module named by the file *path*, without including the
Nick Coghlan76e07702012-07-18 23:14:57 +1000218 names of enclosing packages. The file extension is checked against all of
219 the entries in :func:`importlib.machinery.all_suffixes`. If it matches,
220 the final path component is returned with the extension removed.
221 Otherwise, ``None`` is returned.
222
223 Note that this function *only* returns a meaningful name for actual
224 Python modules - paths that potentially refer to Python packages will
225 still return ``None``.
226
227 .. versionchanged:: 3.3
228 This function is now based directly on :mod:`importlib` rather than the
229 deprecated :func:`getmoduleinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000230
231
232.. function:: ismodule(object)
233
234 Return true if the object is a module.
235
236
237.. function:: isclass(object)
238
Georg Brandl39cadc32010-10-15 16:53:24 +0000239 Return true if the object is a class, whether built-in or created in Python
240 code.
Georg Brandl116aa622007-08-15 14:28:22 +0000241
242
243.. function:: ismethod(object)
244
Georg Brandl39cadc32010-10-15 16:53:24 +0000245 Return true if the object is a bound method written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000246
247
248.. function:: isfunction(object)
249
Georg Brandl39cadc32010-10-15 16:53:24 +0000250 Return true if the object is a Python function, which includes functions
251 created by a :term:`lambda` expression.
Georg Brandl116aa622007-08-15 14:28:22 +0000252
253
Christian Heimes7131fd92008-02-19 14:21:46 +0000254.. function:: isgeneratorfunction(object)
255
256 Return true if the object is a Python generator function.
257
258
259.. function:: isgenerator(object)
260
261 Return true if the object is a generator.
262
263
Georg Brandl116aa622007-08-15 14:28:22 +0000264.. function:: istraceback(object)
265
266 Return true if the object is a traceback.
267
268
269.. function:: isframe(object)
270
271 Return true if the object is a frame.
272
273
274.. function:: iscode(object)
275
276 Return true if the object is a code.
277
278
279.. function:: isbuiltin(object)
280
Georg Brandl39cadc32010-10-15 16:53:24 +0000281 Return true if the object is a built-in function or a bound built-in method.
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283
284.. function:: isroutine(object)
285
286 Return true if the object is a user-defined or built-in function or method.
287
Georg Brandl39cadc32010-10-15 16:53:24 +0000288
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000289.. function:: isabstract(object)
290
291 Return true if the object is an abstract base class.
292
Georg Brandl116aa622007-08-15 14:28:22 +0000293
294.. function:: ismethoddescriptor(object)
295
Georg Brandl39cadc32010-10-15 16:53:24 +0000296 Return true if the object is a method descriptor, but not if
297 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
298 are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000299
Georg Brandle6bcc912008-05-12 18:05:20 +0000300 This, for example, is true of ``int.__add__``. An object passing this test
301 has a :attr:`__get__` attribute but not a :attr:`__set__` attribute, but
302 beyond that the set of attributes varies. :attr:`__name__` is usually
303 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000304
Georg Brandl9afde1c2007-11-01 20:32:30 +0000305 Methods implemented via descriptors that also pass one of the other tests
306 return false from the :func:`ismethoddescriptor` test, simply because the
307 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000308 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000309
310
311.. function:: isdatadescriptor(object)
312
313 Return true if the object is a data descriptor.
314
Georg Brandl9afde1c2007-11-01 20:32:30 +0000315 Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute.
316 Examples are properties (defined in Python), getsets, and members. The
317 latter two are defined in C and there are more specific tests available for
318 those types, which is robust across Python implementations. Typically, data
319 descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes
320 (properties, getsets, and members have both of these attributes), but this is
321 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000322
Georg Brandl116aa622007-08-15 14:28:22 +0000323
324.. function:: isgetsetdescriptor(object)
325
326 Return true if the object is a getset descriptor.
327
Georg Brandl495f7b52009-10-27 15:28:25 +0000328 .. impl-detail::
329
330 getsets are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000331 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000332 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000333
Georg Brandl116aa622007-08-15 14:28:22 +0000334
335.. function:: ismemberdescriptor(object)
336
337 Return true if the object is a member descriptor.
338
Georg Brandl495f7b52009-10-27 15:28:25 +0000339 .. impl-detail::
340
341 Member descriptors are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000342 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000343 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000344
Georg Brandl116aa622007-08-15 14:28:22 +0000345
346.. _inspect-source:
347
348Retrieving source code
349----------------------
350
Georg Brandl116aa622007-08-15 14:28:22 +0000351.. function:: getdoc(object)
352
Georg Brandl0c77a822008-06-10 16:37:50 +0000353 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Georg Brandl116aa622007-08-15 14:28:22 +0000354
355
356.. function:: getcomments(object)
357
358 Return in a single string any lines of comments immediately preceding the
359 object's source code (for a class, function, or method), or at the top of the
360 Python source file (if the object is a module).
361
362
363.. function:: getfile(object)
364
365 Return the name of the (text or binary) file in which an object was defined.
366 This will fail with a :exc:`TypeError` if the object is a built-in module,
367 class, or function.
368
369
370.. function:: getmodule(object)
371
372 Try to guess which module an object was defined in.
373
374
375.. function:: getsourcefile(object)
376
377 Return the name of the Python source file in which an object was defined. This
378 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
379 function.
380
381
382.. function:: getsourcelines(object)
383
384 Return a list of source lines and starting line number for an object. The
385 argument may be a module, class, method, function, traceback, frame, or code
386 object. The source code is returned as a list of the lines corresponding to the
387 object and the line number indicates where in the original source file the first
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200388 line of code was found. An :exc:`OSError` is raised if the source code cannot
Georg Brandl116aa622007-08-15 14:28:22 +0000389 be retrieved.
390
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200391 .. versionchanged:: 3.3
392 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
393 former.
394
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396.. function:: getsource(object)
397
398 Return the text of the source code for an object. The argument may be a module,
399 class, method, function, traceback, frame, or code object. The source code is
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200400 returned as a single string. An :exc:`OSError` is raised if the source code
Georg Brandl116aa622007-08-15 14:28:22 +0000401 cannot be retrieved.
402
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200403 .. versionchanged:: 3.3
404 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
405 former.
406
Georg Brandl116aa622007-08-15 14:28:22 +0000407
Georg Brandl0c77a822008-06-10 16:37:50 +0000408.. function:: cleandoc(doc)
409
410 Clean up indentation from docstrings that are indented to line up with blocks
411 of code. Any whitespace that can be uniformly removed from the second line
412 onwards is removed. Also, all tabs are expanded to spaces.
413
Georg Brandl0c77a822008-06-10 16:37:50 +0000414
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300415.. _inspect-signature-object:
416
Georg Brandle4717722012-08-14 09:45:28 +0200417Introspecting callables with the Signature object
418-------------------------------------------------
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300419
420.. versionadded:: 3.3
421
Georg Brandle4717722012-08-14 09:45:28 +0200422The Signature object represents the call signature of a callable object and its
423return annotation. To retrieve a Signature object, use the :func:`signature`
424function.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300425
426.. function:: signature(callable)
427
Georg Brandle4717722012-08-14 09:45:28 +0200428 Return a :class:`Signature` object for the given ``callable``::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300429
430 >>> from inspect import signature
431 >>> def foo(a, *, b:int, **kwargs):
432 ... pass
433
434 >>> sig = signature(foo)
435
436 >>> str(sig)
437 '(a, *, b:int, **kwargs)'
438
439 >>> str(sig.parameters['b'])
440 'b:int'
441
442 >>> sig.parameters['b'].annotation
443 <class 'int'>
444
Georg Brandle4717722012-08-14 09:45:28 +0200445 Accepts a wide range of python callables, from plain functions and classes to
446 :func:`functools.partial` objects.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300447
Larry Hastings5c661892014-01-24 06:17:25 -0800448 Raises :exc:`ValueError` if no signature can be provided, and
449 :exc:`TypeError` if that type of object is not supported.
450
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300451 .. note::
452
Georg Brandle4717722012-08-14 09:45:28 +0200453 Some callables may not be introspectable in certain implementations of
Yury Selivanovd71e52f2014-01-30 00:22:57 -0500454 Python. For example, in CPython, some built-in functions defined in
455 C provide no metadata about their arguments.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300456
457
Yury Selivanov78356892014-01-30 00:10:54 -0500458.. class:: Signature(parameters=None, \*, return_annotation=Signature.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300459
Georg Brandle4717722012-08-14 09:45:28 +0200460 A Signature object represents the call signature of a function and its return
461 annotation. For each parameter accepted by the function it stores a
462 :class:`Parameter` object in its :attr:`parameters` collection.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300463
Yury Selivanov78356892014-01-30 00:10:54 -0500464 The optional *parameters* argument is a sequence of :class:`Parameter`
465 objects, which is validated to check that there are no parameters with
466 duplicate names, and that the parameters are in the right order, i.e.
467 positional-only first, then positional-or-keyword, and that parameters with
468 defaults follow parameters without defaults.
469
470 The optional *return_annotation* argument, can be an arbitrary Python object,
471 is the "return" annotation of the callable.
472
Georg Brandle4717722012-08-14 09:45:28 +0200473 Signature objects are *immutable*. Use :meth:`Signature.replace` to make a
474 modified copy.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300475
476 .. attribute:: Signature.empty
477
478 A special class-level marker to specify absence of a return annotation.
479
480 .. attribute:: Signature.parameters
481
482 An ordered mapping of parameters' names to the corresponding
483 :class:`Parameter` objects.
484
485 .. attribute:: Signature.return_annotation
486
Georg Brandle4717722012-08-14 09:45:28 +0200487 The "return" annotation for the callable. If the callable has no "return"
488 annotation, this attribute is set to :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300489
490 .. method:: Signature.bind(*args, **kwargs)
491
Georg Brandle4717722012-08-14 09:45:28 +0200492 Create a mapping from positional and keyword arguments to parameters.
493 Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
494 signature, or raises a :exc:`TypeError`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300495
496 .. method:: Signature.bind_partial(*args, **kwargs)
497
Georg Brandle4717722012-08-14 09:45:28 +0200498 Works the same way as :meth:`Signature.bind`, but allows the omission of
499 some required arguments (mimics :func:`functools.partial` behavior.)
500 Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
501 passed arguments do not match the signature.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300502
Ezio Melotti8429b672012-09-14 06:35:09 +0300503 .. method:: Signature.replace(*[, parameters][, return_annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300504
Georg Brandle4717722012-08-14 09:45:28 +0200505 Create a new Signature instance based on the instance replace was invoked
506 on. It is possible to pass different ``parameters`` and/or
507 ``return_annotation`` to override the corresponding properties of the base
508 signature. To remove return_annotation from the copied Signature, pass in
509 :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300510
511 ::
512
513 >>> def test(a, b):
514 ... pass
515 >>> sig = signature(test)
516 >>> new_sig = sig.replace(return_annotation="new return anno")
517 >>> str(new_sig)
518 "(a, b) -> 'new return anno'"
519
520
Yury Selivanov78356892014-01-30 00:10:54 -0500521.. class:: Parameter(name, kind, \*, default=Parameter.empty, annotation=Parameter.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300522
Georg Brandle4717722012-08-14 09:45:28 +0200523 Parameter objects are *immutable*. Instead of modifying a Parameter object,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300524 you can use :meth:`Parameter.replace` to create a modified copy.
525
526 .. attribute:: Parameter.empty
527
Georg Brandle4717722012-08-14 09:45:28 +0200528 A special class-level marker to specify absence of default values and
529 annotations.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300530
531 .. attribute:: Parameter.name
532
Yury Selivanov2393dca2014-01-27 15:07:58 -0500533 The name of the parameter as a string. The name must be a valid
534 Python identifier.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300535
536 .. attribute:: Parameter.default
537
Georg Brandle4717722012-08-14 09:45:28 +0200538 The default value for the parameter. If the parameter has no default
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300539 value, this attribute is set to :attr:`Parameter.empty`.
540
541 .. attribute:: Parameter.annotation
542
Georg Brandle4717722012-08-14 09:45:28 +0200543 The annotation for the parameter. If the parameter has no annotation,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300544 this attribute is set to :attr:`Parameter.empty`.
545
546 .. attribute:: Parameter.kind
547
Georg Brandle4717722012-08-14 09:45:28 +0200548 Describes how argument values are bound to the parameter. Possible values
549 (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300550
Georg Brandl44ea77b2013-03-28 13:28:44 +0100551 .. tabularcolumns:: |l|L|
552
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300553 +------------------------+----------------------------------------------+
554 | Name | Meaning |
555 +========================+==============================================+
556 | *POSITIONAL_ONLY* | Value must be supplied as a positional |
557 | | argument. |
558 | | |
559 | | Python has no explicit syntax for defining |
560 | | positional-only parameters, but many built-in|
561 | | and extension module functions (especially |
562 | | those that accept only one or two parameters)|
563 | | accept them. |
564 +------------------------+----------------------------------------------+
565 | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
566 | | positional argument (this is the standard |
567 | | binding behaviour for functions implemented |
568 | | in Python.) |
569 +------------------------+----------------------------------------------+
570 | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
571 | | bound to any other parameter. This |
572 | | corresponds to a ``*args`` parameter in a |
573 | | Python function definition. |
574 +------------------------+----------------------------------------------+
575 | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
576 | | Keyword only parameters are those which |
577 | | appear after a ``*`` or ``*args`` entry in a |
578 | | Python function definition. |
579 +------------------------+----------------------------------------------+
580 | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
581 | | to any other parameter. This corresponds to a|
582 | | ``**kwargs`` parameter in a Python function |
583 | | definition. |
584 +------------------------+----------------------------------------------+
585
Andrew Svetloveed18082012-08-13 18:23:54 +0300586 Example: print all keyword-only arguments without default values::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300587
588 >>> def foo(a, b, *, c, d=10):
589 ... pass
590
591 >>> sig = signature(foo)
592 >>> for param in sig.parameters.values():
593 ... if (param.kind == param.KEYWORD_ONLY and
594 ... param.default is param.empty):
595 ... print('Parameter:', param)
596 Parameter: c
597
Ezio Melotti8429b672012-09-14 06:35:09 +0300598 .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300599
Georg Brandle4717722012-08-14 09:45:28 +0200600 Create a new Parameter instance based on the instance replaced was invoked
601 on. To override a :class:`Parameter` attribute, pass the corresponding
602 argument. To remove a default value or/and an annotation from a
603 Parameter, pass :attr:`Parameter.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300604
605 ::
606
607 >>> from inspect import Parameter
608 >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
609 >>> str(param)
610 'foo=42'
611
612 >>> str(param.replace()) # Will create a shallow copy of 'param'
613 'foo=42'
614
615 >>> str(param.replace(default=Parameter.empty, annotation='spam'))
616 "foo:'spam'"
617
Yury Selivanov2393dca2014-01-27 15:07:58 -0500618 .. versionchanged:: 3.4
619 In Python 3.3 Parameter objects were allowed to have ``name`` set
620 to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``.
621 This is no longer permitted.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300622
623.. class:: BoundArguments
624
625 Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
626 Holds the mapping of arguments to the function's parameters.
627
628 .. attribute:: BoundArguments.arguments
629
630 An ordered, mutable mapping (:class:`collections.OrderedDict`) of
Georg Brandle4717722012-08-14 09:45:28 +0200631 parameters' names to arguments' values. Contains only explicitly bound
632 arguments. Changes in :attr:`arguments` will reflect in :attr:`args` and
633 :attr:`kwargs`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300634
Georg Brandle4717722012-08-14 09:45:28 +0200635 Should be used in conjunction with :attr:`Signature.parameters` for any
636 argument processing purposes.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300637
638 .. note::
639
640 Arguments for which :meth:`Signature.bind` or
641 :meth:`Signature.bind_partial` relied on a default value are skipped.
Georg Brandle4717722012-08-14 09:45:28 +0200642 However, if needed, it is easy to include them.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300643
644 ::
645
646 >>> def foo(a, b=10):
647 ... pass
648
649 >>> sig = signature(foo)
650 >>> ba = sig.bind(5)
651
652 >>> ba.args, ba.kwargs
653 ((5,), {})
654
655 >>> for param in sig.parameters.values():
Yury Selivanova5ef8322014-12-04 22:47:44 -0500656 ... if (param.name not in ba.arguments
657 ... and param.default is not param.empty):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300658 ... ba.arguments[param.name] = param.default
659
660 >>> ba.args, ba.kwargs
661 ((5, 10), {})
662
663
664 .. attribute:: BoundArguments.args
665
Georg Brandle4717722012-08-14 09:45:28 +0200666 A tuple of positional arguments values. Dynamically computed from the
667 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300668
669 .. attribute:: BoundArguments.kwargs
670
Georg Brandle4717722012-08-14 09:45:28 +0200671 A dict of keyword arguments values. Dynamically computed from the
672 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300673
Yury Selivanov82796192015-05-14 14:14:02 -0400674 .. attribute:: BoundArguments.signature
675
676 A reference to the parent :class:`Signature` object.
677
Georg Brandle4717722012-08-14 09:45:28 +0200678 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
679 functions::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300680
681 def test(a, *, b):
682 ...
683
684 sig = signature(test)
685 ba = sig.bind(10, b=20)
686 test(*ba.args, **ba.kwargs)
687
688
Georg Brandle4717722012-08-14 09:45:28 +0200689.. seealso::
690
691 :pep:`362` - Function Signature Object.
692 The detailed specification, implementation details and examples.
693
694
Georg Brandl116aa622007-08-15 14:28:22 +0000695.. _inspect-classes-functions:
696
697Classes and functions
698---------------------
699
Georg Brandl3dd33882009-06-01 17:35:27 +0000700.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000701
702 Arrange the given list of classes into a hierarchy of nested lists. Where a
703 nested list appears, it contains classes derived from the class whose entry
704 immediately precedes the list. Each entry is a 2-tuple containing a class and a
705 tuple of its base classes. If the *unique* argument is true, exactly one entry
706 appears in the returned structure for each class in the given list. Otherwise,
707 classes using multiple inheritance and their descendants will appear multiple
708 times.
709
710
711.. function:: getargspec(func)
712
Georg Brandl82402752010-01-09 09:48:46 +0000713 Get the names and default values of a Python function's arguments. A
Georg Brandlb30f3302011-01-06 09:23:56 +0000714 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
715 returned. *args* is a list of the argument names. *varargs* and *keywords*
716 are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700717 tuple of default argument values or ``None`` if there are no default
718 arguments; if this tuple has *n* elements, they correspond to the last
719 *n* elements listed in *args*.
Georg Brandl138bcb52007-09-12 19:04:21 +0000720
721 .. deprecated:: 3.0
722 Use :func:`getfullargspec` instead, which provides information about
Benjamin Peterson3e8e9cc2008-11-12 21:26:46 +0000723 keyword-only arguments and annotations.
Georg Brandl138bcb52007-09-12 19:04:21 +0000724
725
726.. function:: getfullargspec(func)
727
Georg Brandl82402752010-01-09 09:48:46 +0000728 Get the names and default values of a Python function's arguments. A
729 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000730
Georg Brandl3dd33882009-06-01 17:35:27 +0000731 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
732 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000733
734 *args* is a list of the argument names. *varargs* and *varkw* are the names
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700735 of the ``*`` and ``**`` arguments or ``None``. *defaults* is an *n*-tuple
736 of the default values of the last *n* arguments, or ``None`` if there are no
737 default arguments. *kwonlyargs* is a list of
Georg Brandl138bcb52007-09-12 19:04:21 +0000738 keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
739 from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
740 names to annotations.
741
742 The first four items in the tuple correspond to :func:`getargspec`.
Georg Brandl116aa622007-08-15 14:28:22 +0000743
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300744 .. note::
745 Consider using the new :ref:`Signature Object <inspect-signature-object>`
746 interface, which provides a better way of introspecting functions.
747
Larry Hastings3732ed22014-03-15 21:13:56 -0700748 .. versionchanged:: 3.4
749 This function is now based on :func:`signature`, but still ignores
750 ``__wrapped__`` attributes and includes the already bound first
751 parameter in the signature output for bound methods.
752
Georg Brandl116aa622007-08-15 14:28:22 +0000753
754.. function:: getargvalues(frame)
755
Georg Brandl3dd33882009-06-01 17:35:27 +0000756 Get information about arguments passed into a particular frame. A
757 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000758 returned. *args* is a list of the argument names. *varargs* and *keywords*
759 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000760 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000761
762
Andrew Svetlov735d3172012-10-27 00:28:20 +0300763.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Georg Brandl116aa622007-08-15 14:28:22 +0000764
Michael Foord3af125a2012-04-21 18:22:28 +0100765 Format a pretty argument spec from the values returned by
766 :func:`getargspec` or :func:`getfullargspec`.
767
768 The first seven arguments are (``args``, ``varargs``, ``varkw``,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100769 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
Andrew Svetlov735d3172012-10-27 00:28:20 +0300770
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100771 The other six arguments are functions that are called to turn argument names,
772 ``*`` argument name, ``**`` argument name, default values, return annotation
773 and individual annotations into strings, respectively.
774
775 For example:
776
777 >>> from inspect import formatargspec, getfullargspec
778 >>> def f(a: int, b: float):
779 ... pass
780 ...
781 >>> formatargspec(*getfullargspec(f))
782 '(a: int, b: float)'
Georg Brandl116aa622007-08-15 14:28:22 +0000783
784
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000785.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000786
787 Format a pretty argument spec from the four values returned by
788 :func:`getargvalues`. The format\* arguments are the corresponding optional
789 formatting functions that are called to turn names and values into strings.
790
791
792.. function:: getmro(cls)
793
794 Return a tuple of class cls's base classes, including cls, in method resolution
795 order. No class appears more than once in this tuple. Note that the method
796 resolution order depends on cls's type. Unless a very peculiar user-defined
797 metatype is in use, cls will be the first element of the tuple.
798
799
Benjamin Peterson3a990c62014-01-02 12:22:30 -0600800.. function:: getcallargs(func, *args, **kwds)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000801
802 Bind the *args* and *kwds* to the argument names of the Python function or
803 method *func*, as if it was called with them. For bound methods, bind also the
804 first argument (typically named ``self``) to the associated instance. A dict
805 is returned, mapping the argument names (including the names of the ``*`` and
806 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
807 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
808 an exception because of incompatible signature, an exception of the same type
809 and the same or similar message is raised. For example::
810
811 >>> from inspect import getcallargs
812 >>> def f(a, b=1, *pos, **named):
813 ... pass
Andrew Svetlove939f382012-08-09 13:25:32 +0300814 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
815 True
816 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
817 True
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000818 >>> getcallargs(f)
819 Traceback (most recent call last):
820 ...
Andrew Svetlove939f382012-08-09 13:25:32 +0300821 TypeError: f() missing 1 required positional argument: 'a'
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000822
823 .. versionadded:: 3.2
824
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300825 .. note::
826 Consider using the new :meth:`Signature.bind` instead.
827
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000828
Nick Coghlan2f92e542012-06-23 19:39:55 +1000829.. function:: getclosurevars(func)
830
831 Get the mapping of external name references in a Python function or
832 method *func* to their current values. A
833 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
834 is returned. *nonlocals* maps referenced names to lexical closure
835 variables, *globals* to the function's module globals and *builtins* to
836 the builtins visible from the function body. *unbound* is the set of names
837 referenced in the function that could not be resolved at all given the
838 current module globals and builtins.
839
840 :exc:`TypeError` is raised if *func* is not a Python function or method.
841
842 .. versionadded:: 3.3
843
844
Nick Coghlane8c45d62013-07-28 20:00:01 +1000845.. function:: unwrap(func, *, stop=None)
846
847 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
848 attributes returning the last object in the chain.
849
850 *stop* is an optional callback accepting an object in the wrapper chain
851 as its sole argument that allows the unwrapping to be terminated early if
852 the callback returns a true value. If the callback never returns a true
853 value, the last object in the chain is returned as usual. For example,
854 :func:`signature` uses this to stop unwrapping if any object in the
855 chain has a ``__signature__`` attribute defined.
856
857 :exc:`ValueError` is raised if a cycle is encountered.
858
859 .. versionadded:: 3.4
860
861
Georg Brandl116aa622007-08-15 14:28:22 +0000862.. _inspect-stack:
863
864The interpreter stack
865---------------------
866
867When the following functions return "frame records," each record is a tuple of
868six items: the frame object, the filename, the line number of the current line,
869the function name, a list of lines of context from the source code, and the
870index of the current line within that list.
871
Georg Brandle720c0a2009-04-27 16:20:50 +0000872.. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000873
874 Keeping references to frame objects, as found in the first element of the frame
875 records these functions return, can cause your program to create reference
876 cycles. Once a reference cycle has been created, the lifespan of all objects
877 which can be accessed from the objects which form the cycle can become much
878 longer even if Python's optional cycle detector is enabled. If such cycles must
879 be created, it is important to ensure they are explicitly broken to avoid the
880 delayed destruction of objects and increased memory consumption which occurs.
881
882 Though the cycle detector will catch these, destruction of the frames (and local
883 variables) can be made deterministic by removing the cycle in a
884 :keyword:`finally` clause. This is also important if the cycle detector was
885 disabled when Python was compiled or using :func:`gc.disable`. For example::
886
887 def handle_stackframe_without_leak():
888 frame = inspect.currentframe()
889 try:
890 # do something with the frame
891 finally:
892 del frame
893
Antoine Pitrou58720d62013-08-05 23:26:40 +0200894 If you want to keep the frame around (for example to print a traceback
895 later), you can also break reference cycles by using the
896 :meth:`frame.clear` method.
897
Georg Brandl116aa622007-08-15 14:28:22 +0000898The optional *context* argument supported by most of these functions specifies
899the number of lines of context to return, which are centered around the current
900line.
901
902
Georg Brandl3dd33882009-06-01 17:35:27 +0000903.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000904
Georg Brandl48310cd2009-01-03 21:18:54 +0000905 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +0000906 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000907
908
Georg Brandl3dd33882009-06-01 17:35:27 +0000909.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000910
911 Get a list of frame records for a frame and all outer frames. These frames
912 represent the calls that lead to the creation of *frame*. The first entry in the
913 returned list represents *frame*; the last entry represents the outermost call
914 on *frame*'s stack.
915
916
Georg Brandl3dd33882009-06-01 17:35:27 +0000917.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000918
919 Get a list of frame records for a traceback's frame and all inner frames. These
920 frames represent calls made as a consequence of *frame*. The first entry in the
921 list represents *traceback*; the last entry represents where the exception was
922 raised.
923
924
925.. function:: currentframe()
926
927 Return the frame object for the caller's stack frame.
928
Georg Brandl495f7b52009-10-27 15:28:25 +0000929 .. impl-detail::
930
931 This function relies on Python stack frame support in the interpreter,
932 which isn't guaranteed to exist in all implementations of Python. If
933 running in an implementation without Python stack frame support this
934 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000935
Georg Brandl116aa622007-08-15 14:28:22 +0000936
Georg Brandl3dd33882009-06-01 17:35:27 +0000937.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000938
939 Return a list of frame records for the caller's stack. The first entry in the
940 returned list represents the caller; the last entry represents the outermost
941 call on the stack.
942
943
Georg Brandl3dd33882009-06-01 17:35:27 +0000944.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000945
946 Return a list of frame records for the stack between the current frame and the
947 frame in which an exception currently being handled was raised in. The first
948 entry in the list represents the caller; the last entry represents where the
949 exception was raised.
950
Michael Foord95fc51d2010-11-20 15:07:30 +0000951
952Fetching attributes statically
953------------------------------
954
955Both :func:`getattr` and :func:`hasattr` can trigger code execution when
956fetching or checking for the existence of attributes. Descriptors, like
957properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
958may be called.
959
960For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +0200961can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +0000962but avoids executing code when it fetches attributes.
963
964.. function:: getattr_static(obj, attr, default=None)
965
966 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +0200967 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +0000968
969 Note: this function may not be able to retrieve all attributes
970 that getattr can fetch (like dynamically created attributes)
971 and may find attributes that getattr can't (like descriptors
972 that raise AttributeError). It can also return descriptors objects
973 instead of instance members.
974
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300975 If the instance :attr:`~object.__dict__` is shadowed by another member (for
976 example a property) then this function will be unable to find instance
977 members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +0000978
Michael Foorddcebe0f2011-03-15 19:20:44 -0400979 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +0000980
Éric Araujo941afed2011-09-01 02:47:34 +0200981:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +0000982getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +0000983is returned instead of the underlying attribute.
984
985You can handle these with code like the following. Note that
986for arbitrary getset descriptors invoking these may trigger
987code execution::
988
989 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +0000990 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +0000991 __slots__ = ['foo']
992
993 slot_descriptor = type(_foo.foo)
994 getset_descriptor = type(type(open(__file__)).name)
995 wrapper_descriptor = type(str.__dict__['__add__'])
996 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
997
998 result = getattr_static(some_object, 'foo')
999 if type(result) in descriptor_types:
1000 try:
1001 result = result.__get__()
1002 except AttributeError:
1003 # descriptors can raise AttributeError to
1004 # indicate there is no underlying value
1005 # in which case the descriptor itself will
1006 # have to do
1007 pass
Nick Coghlane0f04652010-11-21 03:44:04 +00001008
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001009
Nick Coghlane0f04652010-11-21 03:44:04 +00001010Current State of a Generator
1011----------------------------
1012
1013When implementing coroutine schedulers and for other advanced uses of
1014generators, it is useful to determine whether a generator is currently
1015executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001016terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +00001017generator to be determined easily.
1018
1019.. function:: getgeneratorstate(generator)
1020
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001021 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +00001022
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001023 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +00001024 * GEN_CREATED: Waiting to start execution.
1025 * GEN_RUNNING: Currently being executed by the interpreter.
1026 * GEN_SUSPENDED: Currently suspended at a yield expression.
1027 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +00001028
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001029 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001030
1031The current internal state of the generator can also be queried. This is
1032mostly useful for testing purposes, to ensure that internal state is being
1033updated as expected:
1034
1035.. function:: getgeneratorlocals(generator)
1036
1037 Get the mapping of live local variables in *generator* to their current
1038 values. A dictionary is returned that maps from variable names to values.
1039 This is the equivalent of calling :func:`locals` in the body of the
1040 generator, and all the same caveats apply.
1041
1042 If *generator* is a :term:`generator` with no currently associated frame,
1043 then an empty dictionary is returned. :exc:`TypeError` is raised if
1044 *generator* is not a Python generator object.
1045
1046 .. impl-detail::
1047
1048 This function relies on the generator exposing a Python stack frame
1049 for introspection, which isn't guaranteed to be the case in all
1050 implementations of Python. In such cases, this function will always
1051 return an empty dictionary.
1052
1053 .. versionadded:: 3.3
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001054
1055
Nick Coghlan367df122013-10-27 01:57:34 +10001056.. _inspect-module-cli:
1057
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001058Command Line Interface
1059----------------------
1060
1061The :mod:`inspect` module also provides a basic introspection capability
1062from the command line.
1063
1064.. program:: inspect
1065
1066By default, accepts the name of a module and prints the source of that
1067module. A class or function within the module can be printed instead by
1068appended a colon and the qualified name of the target object.
1069
1070.. cmdoption:: --details
1071
1072 Print information about the specified object rather than the source code