blob: fc815a672cec50884dedd4152d353e95916ea23a [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.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Ka-Ping Yee <ping@lfw.org>
8.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
9
Raymond Hettinger469271d2011-01-27 20:38:46 +000010**Source code:** :source:`Lib/inspect.py`
11
12--------------
Georg Brandl116aa622007-08-15 14:28:22 +000013
Georg Brandl116aa622007-08-15 14:28:22 +000014The :mod:`inspect` module provides several useful functions to help get
15information about live objects such as modules, classes, methods, functions,
16tracebacks, frame objects, and code objects. For example, it can help you
17examine the contents of a class, retrieve the source code of a method, extract
18and format the argument list for a function, or get all the information you need
19to display a detailed traceback.
20
21There are four main kinds of services provided by this module: type checking,
22getting source code, inspecting classes and functions, and examining the
23interpreter stack.
24
25
26.. _inspect-types:
27
28Types and members
29-----------------
30
31The :func:`getmembers` function retrieves the members of an object such as a
Yury Selivanov59a3b672015-06-30 22:06:42 -040032class or module. The functions whose names begin with "is" are mainly
Georg Brandl116aa622007-08-15 14:28:22 +000033provided as convenient choices for the second argument to :func:`getmembers`.
34They also help you determine when you can expect to find the following special
35attributes:
36
Eric Snow4f29e752016-09-08 15:11:11 -070037+-----------+-----------------+---------------------------+
38| Type | Attribute | Description |
39+===========+=================+===========================+
40| module | __doc__ | documentation string |
41+-----------+-----------------+---------------------------+
42| | __file__ | filename (missing for |
43| | | built-in modules) |
44+-----------+-----------------+---------------------------+
45| class | __doc__ | documentation string |
46+-----------+-----------------+---------------------------+
47| | __name__ | name with which this |
48| | | class was defined |
49+-----------+-----------------+---------------------------+
50| | __qualname__ | qualified name |
51+-----------+-----------------+---------------------------+
52| | __module__ | name of module in which |
53| | | this class was defined |
54+-----------+-----------------+---------------------------+
55| method | __doc__ | documentation string |
56+-----------+-----------------+---------------------------+
57| | __name__ | name with which this |
58| | | method was defined |
59+-----------+-----------------+---------------------------+
60| | __qualname__ | qualified name |
61+-----------+-----------------+---------------------------+
62| | __func__ | function object |
63| | | containing implementation |
64| | | of method |
65+-----------+-----------------+---------------------------+
66| | __self__ | instance to which this |
67| | | method is bound, or |
68| | | ``None`` |
69+-----------+-----------------+---------------------------+
70| function | __doc__ | documentation string |
71+-----------+-----------------+---------------------------+
72| | __name__ | name with which this |
73| | | function was defined |
74+-----------+-----------------+---------------------------+
75| | __qualname__ | qualified name |
76+-----------+-----------------+---------------------------+
77| | __code__ | code object containing |
78| | | compiled function |
79| | | :term:`bytecode` |
80+-----------+-----------------+---------------------------+
81| | __defaults__ | tuple of any default |
82| | | values for positional or |
83| | | keyword parameters |
84+-----------+-----------------+---------------------------+
85| | __kwdefaults__ | mapping of any default |
86| | | values for keyword-only |
87| | | parameters |
88+-----------+-----------------+---------------------------+
89| | __globals__ | global namespace in which |
90| | | this function was defined |
91+-----------+-----------------+---------------------------+
92| | __annotations__ | mapping of parameters |
93| | | names to annotations; |
94| | | ``"return"`` key is |
95| | | reserved for return |
96| | | annotations. |
97+-----------+-----------------+---------------------------+
98| traceback | tb_frame | frame object at this |
99| | | level |
100+-----------+-----------------+---------------------------+
101| | tb_lasti | index of last attempted |
102| | | instruction in bytecode |
103+-----------+-----------------+---------------------------+
104| | tb_lineno | current line number in |
105| | | Python source code |
106+-----------+-----------------+---------------------------+
107| | tb_next | next inner traceback |
108| | | object (called by this |
109| | | level) |
110+-----------+-----------------+---------------------------+
111| frame | f_back | next outer frame object |
112| | | (this frame's caller) |
113+-----------+-----------------+---------------------------+
114| | f_builtins | builtins namespace seen |
115| | | by this frame |
116+-----------+-----------------+---------------------------+
117| | f_code | code object being |
118| | | executed in this frame |
119+-----------+-----------------+---------------------------+
120| | f_globals | global namespace seen by |
121| | | this frame |
122+-----------+-----------------+---------------------------+
123| | f_lasti | index of last attempted |
124| | | instruction in bytecode |
125+-----------+-----------------+---------------------------+
126| | f_lineno | current line number in |
127| | | Python source code |
128+-----------+-----------------+---------------------------+
129| | f_locals | local namespace seen by |
130| | | this frame |
131+-----------+-----------------+---------------------------+
132| | f_restricted | 0 or 1 if frame is in |
133| | | restricted execution mode |
134+-----------+-----------------+---------------------------+
135| | f_trace | tracing function for this |
136| | | frame, or ``None`` |
137+-----------+-----------------+---------------------------+
138| code | co_argcount | number of arguments (not |
139| | | including \* or \*\* |
140| | | args) |
141+-----------+-----------------+---------------------------+
142| | co_code | string of raw compiled |
143| | | bytecode |
144+-----------+-----------------+---------------------------+
145| | co_consts | tuple of constants used |
146| | | in the bytecode |
147+-----------+-----------------+---------------------------+
148| | co_filename | name of file in which |
149| | | this code object was |
150| | | created |
151+-----------+-----------------+---------------------------+
152| | co_firstlineno | number of first line in |
153| | | Python source code |
154+-----------+-----------------+---------------------------+
Yury Selivanovea75a512016-10-20 13:06:30 -0400155| | co_flags | bitmap of ``CO_*`` flags, |
156| | | read more :ref:`here |
157| | | <inspect-module-co-flags>`|
Eric Snow4f29e752016-09-08 15:11:11 -0700158+-----------+-----------------+---------------------------+
159| | co_lnotab | encoded mapping of line |
160| | | numbers to bytecode |
161| | | indices |
162+-----------+-----------------+---------------------------+
163| | co_name | name with which this code |
164| | | object was defined |
165+-----------+-----------------+---------------------------+
166| | co_names | tuple of names of local |
167| | | variables |
168+-----------+-----------------+---------------------------+
169| | co_nlocals | number of local variables |
170+-----------+-----------------+---------------------------+
171| | co_stacksize | virtual machine stack |
172| | | space required |
173+-----------+-----------------+---------------------------+
174| | co_varnames | tuple of names of |
175| | | arguments and local |
176| | | variables |
177+-----------+-----------------+---------------------------+
178| generator | __name__ | name |
179+-----------+-----------------+---------------------------+
180| | __qualname__ | qualified name |
181+-----------+-----------------+---------------------------+
182| | gi_frame | frame |
183+-----------+-----------------+---------------------------+
184| | gi_running | is the generator running? |
185+-----------+-----------------+---------------------------+
186| | gi_code | code |
187+-----------+-----------------+---------------------------+
188| | gi_yieldfrom | object being iterated by |
189| | | ``yield from``, or |
190| | | ``None`` |
191+-----------+-----------------+---------------------------+
192| coroutine | __name__ | name |
193+-----------+-----------------+---------------------------+
194| | __qualname__ | qualified name |
195+-----------+-----------------+---------------------------+
196| | cr_await | object being awaited on, |
197| | | or ``None`` |
198+-----------+-----------------+---------------------------+
199| | cr_frame | frame |
200+-----------+-----------------+---------------------------+
201| | cr_running | is the coroutine running? |
202+-----------+-----------------+---------------------------+
203| | cr_code | code |
204+-----------+-----------------+---------------------------+
205| builtin | __doc__ | documentation string |
206+-----------+-----------------+---------------------------+
207| | __name__ | original name of this |
208| | | function or method |
209+-----------+-----------------+---------------------------+
210| | __qualname__ | qualified name |
211+-----------+-----------------+---------------------------+
212| | __self__ | instance to which a |
213| | | method is bound, or |
214| | | ``None`` |
215+-----------+-----------------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000216
Victor Stinner40ee3012014-06-16 15:59:28 +0200217.. versionchanged:: 3.5
218
Yury Selivanov5fbad3c2015-08-17 13:04:41 -0400219 Add ``__qualname__`` and ``gi_yieldfrom`` attributes to generators.
220
221 The ``__name__`` attribute of generators is now set from the function
222 name, instead of the code name, and it can now be modified.
Victor Stinner40ee3012014-06-16 15:59:28 +0200223
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225.. function:: getmembers(object[, predicate])
226
227 Return all the members of an object in a list of (name, value) pairs sorted by
228 name. If the optional *predicate* argument is supplied, only members for which
229 the predicate returns a true value are included.
230
Christian Heimes7f044312008-01-06 17:05:40 +0000231 .. note::
232
Ethan Furman63c141c2013-10-18 00:27:39 -0700233 :func:`getmembers` will only return class attributes defined in the
234 metaclass when the argument is a class and those attributes have been
235 listed in the metaclass' custom :meth:`__dir__`.
Christian Heimes7f044312008-01-06 17:05:40 +0000236
Georg Brandl116aa622007-08-15 14:28:22 +0000237
Georg Brandl116aa622007-08-15 14:28:22 +0000238.. function:: getmodulename(path)
239
240 Return the name of the module named by the file *path*, without including the
Nick Coghlan76e07702012-07-18 23:14:57 +1000241 names of enclosing packages. The file extension is checked against all of
242 the entries in :func:`importlib.machinery.all_suffixes`. If it matches,
243 the final path component is returned with the extension removed.
244 Otherwise, ``None`` is returned.
245
246 Note that this function *only* returns a meaningful name for actual
247 Python modules - paths that potentially refer to Python packages will
248 still return ``None``.
249
250 .. versionchanged:: 3.3
Yury Selivanov6dfbc5d2015-07-23 17:49:00 +0300251 The function is based directly on :mod:`importlib`.
Georg Brandl116aa622007-08-15 14:28:22 +0000252
253
254.. function:: ismodule(object)
255
256 Return true if the object is a module.
257
258
259.. function:: isclass(object)
260
Georg Brandl39cadc32010-10-15 16:53:24 +0000261 Return true if the object is a class, whether built-in or created in Python
262 code.
Georg Brandl116aa622007-08-15 14:28:22 +0000263
264
265.. function:: ismethod(object)
266
Georg Brandl39cadc32010-10-15 16:53:24 +0000267 Return true if the object is a bound method written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000268
269
270.. function:: isfunction(object)
271
Georg Brandl39cadc32010-10-15 16:53:24 +0000272 Return true if the object is a Python function, which includes functions
273 created by a :term:`lambda` expression.
Georg Brandl116aa622007-08-15 14:28:22 +0000274
275
Christian Heimes7131fd92008-02-19 14:21:46 +0000276.. function:: isgeneratorfunction(object)
277
278 Return true if the object is a Python generator function.
279
280
281.. function:: isgenerator(object)
282
283 Return true if the object is a generator.
284
285
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400286.. function:: iscoroutinefunction(object)
287
Yury Selivanov5376ba92015-06-22 12:19:30 -0400288 Return true if the object is a :term:`coroutine function`
289 (a function defined with an :keyword:`async def` syntax).
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400290
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400291 .. versionadded:: 3.5
292
293
294.. function:: iscoroutine(object)
295
Yury Selivanov5376ba92015-06-22 12:19:30 -0400296 Return true if the object is a :term:`coroutine` created by an
297 :keyword:`async def` function.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400298
299 .. versionadded:: 3.5
300
301
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400302.. function:: isawaitable(object)
303
304 Return true if the object can be used in :keyword:`await` expression.
305
306 Can also be used to distinguish generator-based coroutines from regular
307 generators::
308
309 def gen():
310 yield
311 @types.coroutine
312 def gen_coro():
313 yield
314
315 assert not isawaitable(gen())
316 assert isawaitable(gen_coro())
317
318 .. versionadded:: 3.5
319
320
Georg Brandl116aa622007-08-15 14:28:22 +0000321.. function:: istraceback(object)
322
323 Return true if the object is a traceback.
324
325
326.. function:: isframe(object)
327
328 Return true if the object is a frame.
329
330
331.. function:: iscode(object)
332
333 Return true if the object is a code.
334
335
336.. function:: isbuiltin(object)
337
Georg Brandl39cadc32010-10-15 16:53:24 +0000338 Return true if the object is a built-in function or a bound built-in method.
Georg Brandl116aa622007-08-15 14:28:22 +0000339
340
341.. function:: isroutine(object)
342
343 Return true if the object is a user-defined or built-in function or method.
344
Georg Brandl39cadc32010-10-15 16:53:24 +0000345
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000346.. function:: isabstract(object)
347
348 Return true if the object is an abstract base class.
349
Georg Brandl116aa622007-08-15 14:28:22 +0000350
351.. function:: ismethoddescriptor(object)
352
Georg Brandl39cadc32010-10-15 16:53:24 +0000353 Return true if the object is a method descriptor, but not if
354 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
355 are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000356
Georg Brandle6bcc912008-05-12 18:05:20 +0000357 This, for example, is true of ``int.__add__``. An object passing this test
Martin Panterbae5d812016-06-18 03:57:31 +0000358 has a :meth:`~object.__get__` method but not a :meth:`~object.__set__`
359 method, but beyond that the set of attributes varies. A
360 :attr:`~definition.__name__` attribute is usually
Georg Brandle6bcc912008-05-12 18:05:20 +0000361 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000362
Georg Brandl9afde1c2007-11-01 20:32:30 +0000363 Methods implemented via descriptors that also pass one of the other tests
364 return false from the :func:`ismethoddescriptor` test, simply because the
365 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000366 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368
369.. function:: isdatadescriptor(object)
370
371 Return true if the object is a data descriptor.
372
Martin Panterbae5d812016-06-18 03:57:31 +0000373 Data descriptors have both a :attr:`~object.__get__` and a :attr:`~object.__set__` method.
Georg Brandl9afde1c2007-11-01 20:32:30 +0000374 Examples are properties (defined in Python), getsets, and members. The
375 latter two are defined in C and there are more specific tests available for
376 those types, which is robust across Python implementations. Typically, data
Martin Panterbae5d812016-06-18 03:57:31 +0000377 descriptors will also have :attr:`~definition.__name__` and :attr:`__doc__` attributes
Georg Brandl9afde1c2007-11-01 20:32:30 +0000378 (properties, getsets, and members have both of these attributes), but this is
379 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000380
Georg Brandl116aa622007-08-15 14:28:22 +0000381
382.. function:: isgetsetdescriptor(object)
383
384 Return true if the object is a getset descriptor.
385
Georg Brandl495f7b52009-10-27 15:28:25 +0000386 .. impl-detail::
387
388 getsets are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000389 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000390 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000391
Georg Brandl116aa622007-08-15 14:28:22 +0000392
393.. function:: ismemberdescriptor(object)
394
395 Return true if the object is a member descriptor.
396
Georg Brandl495f7b52009-10-27 15:28:25 +0000397 .. impl-detail::
398
399 Member descriptors are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000400 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000401 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000402
Georg Brandl116aa622007-08-15 14:28:22 +0000403
404.. _inspect-source:
405
406Retrieving source code
407----------------------
408
Georg Brandl116aa622007-08-15 14:28:22 +0000409.. function:: getdoc(object)
410
Georg Brandl0c77a822008-06-10 16:37:50 +0000411 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300412 If the documentation string for an object is not provided and the object is
413 a class, a method, a property or a descriptor, retrieve the documentation
414 string from the inheritance hierarchy.
Georg Brandl116aa622007-08-15 14:28:22 +0000415
Berker Peksag4333d8b2015-07-30 18:06:09 +0300416 .. versionchanged:: 3.5
417 Documentation strings are now inherited if not overridden.
418
Georg Brandl116aa622007-08-15 14:28:22 +0000419
420.. function:: getcomments(object)
421
422 Return in a single string any lines of comments immediately preceding the
423 object's source code (for a class, function, or method), or at the top of the
424 Python source file (if the object is a module).
425
426
427.. function:: getfile(object)
428
429 Return the name of the (text or binary) file in which an object was defined.
430 This will fail with a :exc:`TypeError` if the object is a built-in module,
431 class, or function.
432
433
434.. function:: getmodule(object)
435
436 Try to guess which module an object was defined in.
437
438
439.. function:: getsourcefile(object)
440
441 Return the name of the Python source file in which an object was defined. This
442 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
443 function.
444
445
446.. function:: getsourcelines(object)
447
448 Return a list of source lines and starting line number for an object. The
449 argument may be a module, class, method, function, traceback, frame, or code
450 object. The source code is returned as a list of the lines corresponding to the
451 object and the line number indicates where in the original source file the first
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200452 line of code was found. An :exc:`OSError` is raised if the source code cannot
Georg Brandl116aa622007-08-15 14:28:22 +0000453 be retrieved.
454
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200455 .. versionchanged:: 3.3
456 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
457 former.
458
Georg Brandl116aa622007-08-15 14:28:22 +0000459
460.. function:: getsource(object)
461
462 Return the text of the source code for an object. The argument may be a module,
463 class, method, function, traceback, frame, or code object. The source code is
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200464 returned as a single string. An :exc:`OSError` is raised if the source code
Georg Brandl116aa622007-08-15 14:28:22 +0000465 cannot be retrieved.
466
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200467 .. versionchanged:: 3.3
468 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
469 former.
470
Georg Brandl116aa622007-08-15 14:28:22 +0000471
Georg Brandl0c77a822008-06-10 16:37:50 +0000472.. function:: cleandoc(doc)
473
474 Clean up indentation from docstrings that are indented to line up with blocks
Senthil Kumaranebd84e32016-05-29 20:36:58 -0700475 of code.
476
477 All leading whitespace is removed from the first line. Any leading whitespace
478 that can be uniformly removed from the second line onwards is removed. Empty
479 lines at the beginning and end are subsequently removed. Also, all tabs are
480 expanded to spaces.
Georg Brandl0c77a822008-06-10 16:37:50 +0000481
Georg Brandl0c77a822008-06-10 16:37:50 +0000482
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300483.. _inspect-signature-object:
484
Georg Brandle4717722012-08-14 09:45:28 +0200485Introspecting callables with the Signature object
486-------------------------------------------------
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300487
488.. versionadded:: 3.3
489
Georg Brandle4717722012-08-14 09:45:28 +0200490The Signature object represents the call signature of a callable object and its
491return annotation. To retrieve a Signature object, use the :func:`signature`
492function.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300493
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400494.. function:: signature(callable, \*, follow_wrapped=True)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300495
Georg Brandle4717722012-08-14 09:45:28 +0200496 Return a :class:`Signature` object for the given ``callable``::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300497
498 >>> from inspect import signature
499 >>> def foo(a, *, b:int, **kwargs):
500 ... pass
501
502 >>> sig = signature(foo)
503
504 >>> str(sig)
505 '(a, *, b:int, **kwargs)'
506
507 >>> str(sig.parameters['b'])
508 'b:int'
509
510 >>> sig.parameters['b'].annotation
511 <class 'int'>
512
Georg Brandle4717722012-08-14 09:45:28 +0200513 Accepts a wide range of python callables, from plain functions and classes to
514 :func:`functools.partial` objects.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300515
Larry Hastings5c661892014-01-24 06:17:25 -0800516 Raises :exc:`ValueError` if no signature can be provided, and
517 :exc:`TypeError` if that type of object is not supported.
518
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400519 .. versionadded:: 3.5
520 ``follow_wrapped`` parameter. Pass ``False`` to get a signature of
521 ``callable`` specifically (``callable.__wrapped__`` will not be used to
522 unwrap decorated callables.)
523
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300524 .. note::
525
Georg Brandle4717722012-08-14 09:45:28 +0200526 Some callables may not be introspectable in certain implementations of
Yury Selivanovd71e52f2014-01-30 00:22:57 -0500527 Python. For example, in CPython, some built-in functions defined in
528 C provide no metadata about their arguments.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300529
530
Yury Selivanov78356892014-01-30 00:10:54 -0500531.. class:: Signature(parameters=None, \*, return_annotation=Signature.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300532
Georg Brandle4717722012-08-14 09:45:28 +0200533 A Signature object represents the call signature of a function and its return
534 annotation. For each parameter accepted by the function it stores a
535 :class:`Parameter` object in its :attr:`parameters` collection.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300536
Yury Selivanov78356892014-01-30 00:10:54 -0500537 The optional *parameters* argument is a sequence of :class:`Parameter`
538 objects, which is validated to check that there are no parameters with
539 duplicate names, and that the parameters are in the right order, i.e.
540 positional-only first, then positional-or-keyword, and that parameters with
541 defaults follow parameters without defaults.
542
543 The optional *return_annotation* argument, can be an arbitrary Python object,
544 is the "return" annotation of the callable.
545
Georg Brandle4717722012-08-14 09:45:28 +0200546 Signature objects are *immutable*. Use :meth:`Signature.replace` to make a
547 modified copy.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300548
Yury Selivanov67d727e2014-03-29 13:24:14 -0400549 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400550 Signature objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400551
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300552 .. attribute:: Signature.empty
553
554 A special class-level marker to specify absence of a return annotation.
555
556 .. attribute:: Signature.parameters
557
558 An ordered mapping of parameters' names to the corresponding
559 :class:`Parameter` objects.
560
561 .. attribute:: Signature.return_annotation
562
Georg Brandle4717722012-08-14 09:45:28 +0200563 The "return" annotation for the callable. If the callable has no "return"
564 annotation, this attribute is set to :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300565
566 .. method:: Signature.bind(*args, **kwargs)
567
Georg Brandle4717722012-08-14 09:45:28 +0200568 Create a mapping from positional and keyword arguments to parameters.
569 Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
570 signature, or raises a :exc:`TypeError`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300571
572 .. method:: Signature.bind_partial(*args, **kwargs)
573
Georg Brandle4717722012-08-14 09:45:28 +0200574 Works the same way as :meth:`Signature.bind`, but allows the omission of
575 some required arguments (mimics :func:`functools.partial` behavior.)
576 Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
577 passed arguments do not match the signature.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300578
Ezio Melotti8429b672012-09-14 06:35:09 +0300579 .. method:: Signature.replace(*[, parameters][, return_annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300580
Georg Brandle4717722012-08-14 09:45:28 +0200581 Create a new Signature instance based on the instance replace was invoked
582 on. It is possible to pass different ``parameters`` and/or
583 ``return_annotation`` to override the corresponding properties of the base
584 signature. To remove return_annotation from the copied Signature, pass in
585 :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300586
587 ::
588
589 >>> def test(a, b):
590 ... pass
591 >>> sig = signature(test)
592 >>> new_sig = sig.replace(return_annotation="new return anno")
593 >>> str(new_sig)
594 "(a, b) -> 'new return anno'"
595
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400596 .. classmethod:: Signature.from_callable(obj, \*, follow_wrapped=True)
Yury Selivanovda396452014-03-27 12:09:24 -0400597
598 Return a :class:`Signature` (or its subclass) object for a given callable
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400599 ``obj``. Pass ``follow_wrapped=False`` to get a signature of ``obj``
600 without unwrapping its ``__wrapped__`` chain.
Yury Selivanovda396452014-03-27 12:09:24 -0400601
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400602 This method simplifies subclassing of :class:`Signature`::
Yury Selivanovda396452014-03-27 12:09:24 -0400603
604 class MySignature(Signature):
605 pass
606 sig = MySignature.from_callable(min)
607 assert isinstance(sig, MySignature)
608
Yury Selivanov232b9342014-03-29 13:18:30 -0400609 .. versionadded:: 3.5
610
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300611
Yury Selivanov78356892014-01-30 00:10:54 -0500612.. class:: Parameter(name, kind, \*, default=Parameter.empty, annotation=Parameter.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300613
Georg Brandle4717722012-08-14 09:45:28 +0200614 Parameter objects are *immutable*. Instead of modifying a Parameter object,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300615 you can use :meth:`Parameter.replace` to create a modified copy.
616
Yury Selivanov67d727e2014-03-29 13:24:14 -0400617 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400618 Parameter objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400619
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300620 .. attribute:: Parameter.empty
621
Georg Brandle4717722012-08-14 09:45:28 +0200622 A special class-level marker to specify absence of default values and
623 annotations.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300624
625 .. attribute:: Parameter.name
626
Yury Selivanov2393dca2014-01-27 15:07:58 -0500627 The name of the parameter as a string. The name must be a valid
628 Python identifier.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300629
Nick Coghlanb4b966e2016-06-04 14:40:03 -0700630 .. impl-detail::
631
632 CPython generates implicit parameter names of the form ``.0`` on the
633 code objects used to implement comprehensions and generator
634 expressions.
635
636 .. versionchanged:: 3.6
637 These parameter names are exposed by this module as names like
638 ``implicit0``.
639
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300640 .. attribute:: Parameter.default
641
Georg Brandle4717722012-08-14 09:45:28 +0200642 The default value for the parameter. If the parameter has no default
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300643 value, this attribute is set to :attr:`Parameter.empty`.
644
645 .. attribute:: Parameter.annotation
646
Georg Brandle4717722012-08-14 09:45:28 +0200647 The annotation for the parameter. If the parameter has no annotation,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300648 this attribute is set to :attr:`Parameter.empty`.
649
650 .. attribute:: Parameter.kind
651
Georg Brandle4717722012-08-14 09:45:28 +0200652 Describes how argument values are bound to the parameter. Possible values
653 (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300654
Georg Brandl44ea77b2013-03-28 13:28:44 +0100655 .. tabularcolumns:: |l|L|
656
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300657 +------------------------+----------------------------------------------+
658 | Name | Meaning |
659 +========================+==============================================+
660 | *POSITIONAL_ONLY* | Value must be supplied as a positional |
661 | | argument. |
662 | | |
663 | | Python has no explicit syntax for defining |
664 | | positional-only parameters, but many built-in|
665 | | and extension module functions (especially |
666 | | those that accept only one or two parameters)|
667 | | accept them. |
668 +------------------------+----------------------------------------------+
669 | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
670 | | positional argument (this is the standard |
671 | | binding behaviour for functions implemented |
672 | | in Python.) |
673 +------------------------+----------------------------------------------+
674 | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
675 | | bound to any other parameter. This |
676 | | corresponds to a ``*args`` parameter in a |
677 | | Python function definition. |
678 +------------------------+----------------------------------------------+
679 | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
680 | | Keyword only parameters are those which |
681 | | appear after a ``*`` or ``*args`` entry in a |
682 | | Python function definition. |
683 +------------------------+----------------------------------------------+
684 | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
685 | | to any other parameter. This corresponds to a|
686 | | ``**kwargs`` parameter in a Python function |
687 | | definition. |
688 +------------------------+----------------------------------------------+
689
Andrew Svetloveed18082012-08-13 18:23:54 +0300690 Example: print all keyword-only arguments without default values::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300691
692 >>> def foo(a, b, *, c, d=10):
693 ... pass
694
695 >>> sig = signature(foo)
696 >>> for param in sig.parameters.values():
697 ... if (param.kind == param.KEYWORD_ONLY and
698 ... param.default is param.empty):
699 ... print('Parameter:', param)
700 Parameter: c
701
Ezio Melotti8429b672012-09-14 06:35:09 +0300702 .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300703
Georg Brandle4717722012-08-14 09:45:28 +0200704 Create a new Parameter instance based on the instance replaced was invoked
705 on. To override a :class:`Parameter` attribute, pass the corresponding
706 argument. To remove a default value or/and an annotation from a
707 Parameter, pass :attr:`Parameter.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300708
709 ::
710
711 >>> from inspect import Parameter
712 >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
713 >>> str(param)
714 'foo=42'
715
716 >>> str(param.replace()) # Will create a shallow copy of 'param'
717 'foo=42'
718
719 >>> str(param.replace(default=Parameter.empty, annotation='spam'))
720 "foo:'spam'"
721
Yury Selivanov2393dca2014-01-27 15:07:58 -0500722 .. versionchanged:: 3.4
723 In Python 3.3 Parameter objects were allowed to have ``name`` set
724 to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``.
725 This is no longer permitted.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300726
727.. class:: BoundArguments
728
729 Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
730 Holds the mapping of arguments to the function's parameters.
731
732 .. attribute:: BoundArguments.arguments
733
734 An ordered, mutable mapping (:class:`collections.OrderedDict`) of
Georg Brandle4717722012-08-14 09:45:28 +0200735 parameters' names to arguments' values. Contains only explicitly bound
736 arguments. Changes in :attr:`arguments` will reflect in :attr:`args` and
737 :attr:`kwargs`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300738
Georg Brandle4717722012-08-14 09:45:28 +0200739 Should be used in conjunction with :attr:`Signature.parameters` for any
740 argument processing purposes.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300741
742 .. note::
743
744 Arguments for which :meth:`Signature.bind` or
745 :meth:`Signature.bind_partial` relied on a default value are skipped.
Yury Selivanovb907a512015-05-16 13:45:09 -0400746 However, if needed, use :meth:`BoundArguments.apply_defaults` to add
747 them.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300748
749 .. attribute:: BoundArguments.args
750
Georg Brandle4717722012-08-14 09:45:28 +0200751 A tuple of positional arguments values. Dynamically computed from the
752 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300753
754 .. attribute:: BoundArguments.kwargs
755
Georg Brandle4717722012-08-14 09:45:28 +0200756 A dict of keyword arguments values. Dynamically computed from the
757 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300758
Yury Selivanov82796192015-05-14 14:14:02 -0400759 .. attribute:: BoundArguments.signature
760
761 A reference to the parent :class:`Signature` object.
762
Yury Selivanovb907a512015-05-16 13:45:09 -0400763 .. method:: BoundArguments.apply_defaults()
764
765 Set default values for missing arguments.
766
767 For variable-positional arguments (``*args``) the default is an
768 empty tuple.
769
770 For variable-keyword arguments (``**kwargs``) the default is an
771 empty dict.
772
773 ::
774
775 >>> def foo(a, b='ham', *args): pass
776 >>> ba = inspect.signature(foo).bind('spam')
777 >>> ba.apply_defaults()
778 >>> ba.arguments
779 OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])
780
Berker Peksag5b3df5b2015-05-16 23:29:31 +0300781 .. versionadded:: 3.5
782
Georg Brandle4717722012-08-14 09:45:28 +0200783 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
784 functions::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300785
786 def test(a, *, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300787 ...
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300788
789 sig = signature(test)
790 ba = sig.bind(10, b=20)
791 test(*ba.args, **ba.kwargs)
792
793
Georg Brandle4717722012-08-14 09:45:28 +0200794.. seealso::
795
796 :pep:`362` - Function Signature Object.
797 The detailed specification, implementation details and examples.
798
799
Georg Brandl116aa622007-08-15 14:28:22 +0000800.. _inspect-classes-functions:
801
802Classes and functions
803---------------------
804
Georg Brandl3dd33882009-06-01 17:35:27 +0000805.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000806
807 Arrange the given list of classes into a hierarchy of nested lists. Where a
808 nested list appears, it contains classes derived from the class whose entry
809 immediately precedes the list. Each entry is a 2-tuple containing a class and a
810 tuple of its base classes. If the *unique* argument is true, exactly one entry
811 appears in the returned structure for each class in the given list. Otherwise,
812 classes using multiple inheritance and their descendants will appear multiple
813 times.
814
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500815
816.. function:: getargspec(func)
817
818 Get the names and default values of a Python function's arguments. A
819 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
820 returned. *args* is a list of the argument names. *varargs* and *keywords*
821 are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a
822 tuple of default argument values or ``None`` if there are no default
823 arguments; if this tuple has *n* elements, they correspond to the last
824 *n* elements listed in *args*.
825
826 .. deprecated:: 3.0
827 Use :func:`signature` and
828 :ref:`Signature Object <inspect-signature-object>`, which provide a
Yury Selivanova7c159d2016-01-11 21:04:50 -0500829 better introspecting API for callables.
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500830
831
Georg Brandl138bcb52007-09-12 19:04:21 +0000832.. function:: getfullargspec(func)
833
Georg Brandl82402752010-01-09 09:48:46 +0000834 Get the names and default values of a Python function's arguments. A
835 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000836
Georg Brandl3dd33882009-06-01 17:35:27 +0000837 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
838 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000839
840 *args* is a list of the argument names. *varargs* and *varkw* are the names
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700841 of the ``*`` and ``**`` arguments or ``None``. *defaults* is an *n*-tuple
842 of the default values of the last *n* arguments, or ``None`` if there are no
843 default arguments. *kwonlyargs* is a list of
Georg Brandl138bcb52007-09-12 19:04:21 +0000844 keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
845 from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
846 names to annotations.
847
Nick Coghlan16355782014-03-08 16:36:37 +1000848 .. versionchanged:: 3.4
849 This function is now based on :func:`signature`, but still ignores
850 ``__wrapped__`` attributes and includes the already bound first
851 parameter in the signature output for bound methods.
852
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400853 .. deprecated:: 3.5
854 Use :func:`signature` and
855 :ref:`Signature Object <inspect-signature-object>`, which provide a
856 better introspecting API for callables.
857
Georg Brandl116aa622007-08-15 14:28:22 +0000858
859.. function:: getargvalues(frame)
860
Georg Brandl3dd33882009-06-01 17:35:27 +0000861 Get information about arguments passed into a particular frame. A
862 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000863 returned. *args* is a list of the argument names. *varargs* and *keywords*
864 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000865 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000866
Yury Selivanov945fff42015-05-22 16:28:05 -0400867 .. deprecated:: 3.5
868 Use :func:`signature` and
869 :ref:`Signature Object <inspect-signature-object>`, which provide a
870 better introspecting API for callables.
871
Georg Brandl116aa622007-08-15 14:28:22 +0000872
Andrew Svetlov735d3172012-10-27 00:28:20 +0300873.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Georg Brandl116aa622007-08-15 14:28:22 +0000874
Michael Foord3af125a2012-04-21 18:22:28 +0100875 Format a pretty argument spec from the values returned by
Berker Peksagfa3922c2015-07-31 04:11:29 +0300876 :func:`getfullargspec`.
Michael Foord3af125a2012-04-21 18:22:28 +0100877
878 The first seven arguments are (``args``, ``varargs``, ``varkw``,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100879 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
Andrew Svetlov735d3172012-10-27 00:28:20 +0300880
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100881 The other six arguments are functions that are called to turn argument names,
882 ``*`` argument name, ``**`` argument name, default values, return annotation
883 and individual annotations into strings, respectively.
884
885 For example:
886
887 >>> from inspect import formatargspec, getfullargspec
888 >>> def f(a: int, b: float):
889 ... pass
890 ...
891 >>> formatargspec(*getfullargspec(f))
892 '(a: int, b: float)'
Georg Brandl116aa622007-08-15 14:28:22 +0000893
Yury Selivanov945fff42015-05-22 16:28:05 -0400894 .. deprecated:: 3.5
895 Use :func:`signature` and
896 :ref:`Signature Object <inspect-signature-object>`, which provide a
897 better introspecting API for callables.
898
Georg Brandl116aa622007-08-15 14:28:22 +0000899
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000900.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000901
902 Format a pretty argument spec from the four values returned by
903 :func:`getargvalues`. The format\* arguments are the corresponding optional
904 formatting functions that are called to turn names and values into strings.
905
Yury Selivanov945fff42015-05-22 16:28:05 -0400906 .. deprecated:: 3.5
907 Use :func:`signature` and
908 :ref:`Signature Object <inspect-signature-object>`, which provide a
909 better introspecting API for callables.
910
Georg Brandl116aa622007-08-15 14:28:22 +0000911
912.. function:: getmro(cls)
913
914 Return a tuple of class cls's base classes, including cls, in method resolution
915 order. No class appears more than once in this tuple. Note that the method
916 resolution order depends on cls's type. Unless a very peculiar user-defined
917 metatype is in use, cls will be the first element of the tuple.
918
919
Benjamin Peterson3a990c62014-01-02 12:22:30 -0600920.. function:: getcallargs(func, *args, **kwds)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000921
922 Bind the *args* and *kwds* to the argument names of the Python function or
923 method *func*, as if it was called with them. For bound methods, bind also the
924 first argument (typically named ``self``) to the associated instance. A dict
925 is returned, mapping the argument names (including the names of the ``*`` and
926 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
927 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
928 an exception because of incompatible signature, an exception of the same type
929 and the same or similar message is raised. For example::
930
931 >>> from inspect import getcallargs
932 >>> def f(a, b=1, *pos, **named):
933 ... pass
Andrew Svetlove939f382012-08-09 13:25:32 +0300934 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
935 True
936 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
937 True
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000938 >>> getcallargs(f)
939 Traceback (most recent call last):
940 ...
Andrew Svetlove939f382012-08-09 13:25:32 +0300941 TypeError: f() missing 1 required positional argument: 'a'
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000942
943 .. versionadded:: 3.2
944
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400945 .. deprecated:: 3.5
946 Use :meth:`Signature.bind` and :meth:`Signature.bind_partial` instead.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300947
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000948
Nick Coghlan2f92e542012-06-23 19:39:55 +1000949.. function:: getclosurevars(func)
950
951 Get the mapping of external name references in a Python function or
952 method *func* to their current values. A
953 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
954 is returned. *nonlocals* maps referenced names to lexical closure
955 variables, *globals* to the function's module globals and *builtins* to
956 the builtins visible from the function body. *unbound* is the set of names
957 referenced in the function that could not be resolved at all given the
958 current module globals and builtins.
959
960 :exc:`TypeError` is raised if *func* is not a Python function or method.
961
962 .. versionadded:: 3.3
963
964
Nick Coghlane8c45d62013-07-28 20:00:01 +1000965.. function:: unwrap(func, *, stop=None)
966
967 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
968 attributes returning the last object in the chain.
969
970 *stop* is an optional callback accepting an object in the wrapper chain
971 as its sole argument that allows the unwrapping to be terminated early if
972 the callback returns a true value. If the callback never returns a true
973 value, the last object in the chain is returned as usual. For example,
974 :func:`signature` uses this to stop unwrapping if any object in the
975 chain has a ``__signature__`` attribute defined.
976
977 :exc:`ValueError` is raised if a cycle is encountered.
978
979 .. versionadded:: 3.4
980
981
Georg Brandl116aa622007-08-15 14:28:22 +0000982.. _inspect-stack:
983
984The interpreter stack
985---------------------
986
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400987When the following functions return "frame records," each record is a
988:term:`named tuple`
989``FrameInfo(frame, filename, lineno, function, code_context, index)``.
990The tuple contains the frame object, the filename, the line number of the
991current line,
Georg Brandl116aa622007-08-15 14:28:22 +0000992the function name, a list of lines of context from the source code, and the
993index of the current line within that list.
994
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400995.. versionchanged:: 3.5
996 Return a named tuple instead of a tuple.
997
Georg Brandle720c0a2009-04-27 16:20:50 +0000998.. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000999
1000 Keeping references to frame objects, as found in the first element of the frame
1001 records these functions return, can cause your program to create reference
1002 cycles. Once a reference cycle has been created, the lifespan of all objects
1003 which can be accessed from the objects which form the cycle can become much
1004 longer even if Python's optional cycle detector is enabled. If such cycles must
1005 be created, it is important to ensure they are explicitly broken to avoid the
1006 delayed destruction of objects and increased memory consumption which occurs.
1007
1008 Though the cycle detector will catch these, destruction of the frames (and local
1009 variables) can be made deterministic by removing the cycle in a
1010 :keyword:`finally` clause. This is also important if the cycle detector was
1011 disabled when Python was compiled or using :func:`gc.disable`. For example::
1012
1013 def handle_stackframe_without_leak():
1014 frame = inspect.currentframe()
1015 try:
1016 # do something with the frame
1017 finally:
1018 del frame
1019
Antoine Pitrou58720d62013-08-05 23:26:40 +02001020 If you want to keep the frame around (for example to print a traceback
1021 later), you can also break reference cycles by using the
1022 :meth:`frame.clear` method.
1023
Georg Brandl116aa622007-08-15 14:28:22 +00001024The optional *context* argument supported by most of these functions specifies
1025the number of lines of context to return, which are centered around the current
1026line.
1027
1028
Georg Brandl3dd33882009-06-01 17:35:27 +00001029.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001030
Georg Brandl48310cd2009-01-03 21:18:54 +00001031 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +00001032 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +00001033
1034
Georg Brandl3dd33882009-06-01 17:35:27 +00001035.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001036
1037 Get a list of frame records for a frame and all outer frames. These frames
1038 represent the calls that lead to the creation of *frame*. The first entry in the
1039 returned list represents *frame*; the last entry represents the outermost call
1040 on *frame*'s stack.
1041
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001042 .. versionchanged:: 3.5
1043 A list of :term:`named tuples <named tuple>`
1044 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1045 is returned.
1046
Georg Brandl116aa622007-08-15 14:28:22 +00001047
Georg Brandl3dd33882009-06-01 17:35:27 +00001048.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001049
1050 Get a list of frame records for a traceback's frame and all inner frames. These
1051 frames represent calls made as a consequence of *frame*. The first entry in the
1052 list represents *traceback*; the last entry represents where the exception was
1053 raised.
1054
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001055 .. versionchanged:: 3.5
1056 A list of :term:`named tuples <named tuple>`
1057 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1058 is returned.
1059
Georg Brandl116aa622007-08-15 14:28:22 +00001060
1061.. function:: currentframe()
1062
1063 Return the frame object for the caller's stack frame.
1064
Georg Brandl495f7b52009-10-27 15:28:25 +00001065 .. impl-detail::
1066
1067 This function relies on Python stack frame support in the interpreter,
1068 which isn't guaranteed to exist in all implementations of Python. If
1069 running in an implementation without Python stack frame support this
1070 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001071
Georg Brandl116aa622007-08-15 14:28:22 +00001072
Georg Brandl3dd33882009-06-01 17:35:27 +00001073.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001074
1075 Return a list of frame records for the caller's stack. The first entry in the
1076 returned list represents the caller; the last entry represents the outermost
1077 call on the stack.
1078
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001079 .. versionchanged:: 3.5
1080 A list of :term:`named tuples <named tuple>`
1081 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1082 is returned.
1083
Georg Brandl116aa622007-08-15 14:28:22 +00001084
Georg Brandl3dd33882009-06-01 17:35:27 +00001085.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001086
1087 Return a list of frame records for the stack between the current frame and the
1088 frame in which an exception currently being handled was raised in. The first
1089 entry in the list represents the caller; the last entry represents where the
1090 exception was raised.
1091
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001092 .. versionchanged:: 3.5
1093 A list of :term:`named tuples <named tuple>`
1094 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1095 is returned.
1096
Michael Foord95fc51d2010-11-20 15:07:30 +00001097
1098Fetching attributes statically
1099------------------------------
1100
1101Both :func:`getattr` and :func:`hasattr` can trigger code execution when
1102fetching or checking for the existence of attributes. Descriptors, like
1103properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
1104may be called.
1105
1106For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +02001107can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +00001108but avoids executing code when it fetches attributes.
1109
1110.. function:: getattr_static(obj, attr, default=None)
1111
1112 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +02001113 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +00001114
1115 Note: this function may not be able to retrieve all attributes
1116 that getattr can fetch (like dynamically created attributes)
1117 and may find attributes that getattr can't (like descriptors
1118 that raise AttributeError). It can also return descriptors objects
1119 instead of instance members.
1120
Serhiy Storchakabfdcd432013-10-13 23:09:14 +03001121 If the instance :attr:`~object.__dict__` is shadowed by another member (for
1122 example a property) then this function will be unable to find instance
1123 members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001124
Michael Foorddcebe0f2011-03-15 19:20:44 -04001125 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +00001126
Éric Araujo941afed2011-09-01 02:47:34 +02001127:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +00001128getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +00001129is returned instead of the underlying attribute.
1130
1131You can handle these with code like the following. Note that
1132for arbitrary getset descriptors invoking these may trigger
1133code execution::
1134
1135 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +00001136 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +00001137 __slots__ = ['foo']
1138
1139 slot_descriptor = type(_foo.foo)
1140 getset_descriptor = type(type(open(__file__)).name)
1141 wrapper_descriptor = type(str.__dict__['__add__'])
1142 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
1143
1144 result = getattr_static(some_object, 'foo')
1145 if type(result) in descriptor_types:
1146 try:
1147 result = result.__get__()
1148 except AttributeError:
1149 # descriptors can raise AttributeError to
1150 # indicate there is no underlying value
1151 # in which case the descriptor itself will
1152 # have to do
1153 pass
Nick Coghlane0f04652010-11-21 03:44:04 +00001154
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001155
Yury Selivanov5376ba92015-06-22 12:19:30 -04001156Current State of Generators and Coroutines
1157------------------------------------------
Nick Coghlane0f04652010-11-21 03:44:04 +00001158
1159When implementing coroutine schedulers and for other advanced uses of
1160generators, it is useful to determine whether a generator is currently
1161executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001162terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +00001163generator to be determined easily.
1164
1165.. function:: getgeneratorstate(generator)
1166
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001167 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +00001168
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001169 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +00001170 * GEN_CREATED: Waiting to start execution.
1171 * GEN_RUNNING: Currently being executed by the interpreter.
1172 * GEN_SUSPENDED: Currently suspended at a yield expression.
1173 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +00001174
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001175 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001176
Yury Selivanov5376ba92015-06-22 12:19:30 -04001177.. function:: getcoroutinestate(coroutine)
1178
1179 Get current state of a coroutine object. The function is intended to be
1180 used with coroutine objects created by :keyword:`async def` functions, but
1181 will accept any coroutine-like object that has ``cr_running`` and
1182 ``cr_frame`` attributes.
1183
1184 Possible states are:
1185 * CORO_CREATED: Waiting to start execution.
1186 * CORO_RUNNING: Currently being executed by the interpreter.
1187 * CORO_SUSPENDED: Currently suspended at an await expression.
1188 * CORO_CLOSED: Execution has completed.
1189
1190 .. versionadded:: 3.5
1191
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001192The current internal state of the generator can also be queried. This is
1193mostly useful for testing purposes, to ensure that internal state is being
1194updated as expected:
1195
1196.. function:: getgeneratorlocals(generator)
1197
1198 Get the mapping of live local variables in *generator* to their current
1199 values. A dictionary is returned that maps from variable names to values.
1200 This is the equivalent of calling :func:`locals` in the body of the
1201 generator, and all the same caveats apply.
1202
1203 If *generator* is a :term:`generator` with no currently associated frame,
1204 then an empty dictionary is returned. :exc:`TypeError` is raised if
1205 *generator* is not a Python generator object.
1206
1207 .. impl-detail::
1208
1209 This function relies on the generator exposing a Python stack frame
1210 for introspection, which isn't guaranteed to be the case in all
1211 implementations of Python. In such cases, this function will always
1212 return an empty dictionary.
1213
1214 .. versionadded:: 3.3
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001215
Yury Selivanov5376ba92015-06-22 12:19:30 -04001216.. function:: getcoroutinelocals(coroutine)
1217
1218 This function is analogous to :func:`~inspect.getgeneratorlocals`, but
1219 works for coroutine objects created by :keyword:`async def` functions.
1220
1221 .. versionadded:: 3.5
1222
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001223
Yury Selivanovea75a512016-10-20 13:06:30 -04001224.. _inspect-module-co-flags:
1225
1226Code Objects Bit Flags
1227----------------------
1228
1229Python code objects have a ``co_flags`` attribute, which is a bitmap of
1230the following flags:
1231
1232.. data:: CO_NEWLOCALS
1233
1234 If set, a new dict will be created for the frame's ``f_locals`` when
1235 the code object is executed.
1236
1237.. data:: CO_VARARGS
1238
1239 The code object has a variable positional parameter (``*args``-like).
1240
1241.. data:: CO_VARKEYWORDS
1242
1243 The code object has a variable keyword parameter (``**kwargs``-like).
1244
1245.. data:: CO_GENERATOR
1246
1247 The flag is set when the code object is a generator function, i.e.
1248 a generator object is returned when the code object is executed.
1249
1250.. data:: CO_NOFREE
1251
1252 The flag is set if there are no free or cell variables.
1253
1254.. data:: CO_COROUTINE
1255
Yury Selivanovb738a1f2016-10-20 16:30:51 -04001256 The flag is set when the code object is a coroutine function.
1257 When the code object is executed it returns a coroutine object.
1258 See :pep:`492` for more details.
Yury Selivanovea75a512016-10-20 13:06:30 -04001259
1260 .. versionadded:: 3.5
1261
1262.. data:: CO_ITERABLE_COROUTINE
1263
Yury Selivanovb738a1f2016-10-20 16:30:51 -04001264 The flag is used to transform generators into generator-based
1265 coroutines. Generator objects with this flag can be used in
1266 ``await`` expression, and can ``yield from`` coroutine objects.
1267 See :pep:`492` for more details.
Yury Selivanovea75a512016-10-20 13:06:30 -04001268
1269 .. versionadded:: 3.5
1270
Yury Selivanove20fed92016-10-20 13:11:34 -04001271.. data:: CO_ASYNC_GENERATOR
1272
Yury Selivanovb738a1f2016-10-20 16:30:51 -04001273 The flag is set when the code object is an asynchronous generator
1274 function. When the code object is executed it returns an
1275 asynchronous generator object. See :pep:`525` for more details.
Yury Selivanove20fed92016-10-20 13:11:34 -04001276
1277 .. versionadded:: 3.6
1278
Yury Selivanovea75a512016-10-20 13:06:30 -04001279.. note::
1280 The flags are specific to CPython, and may not be defined in other
1281 Python implementations. Furthermore, the flags are an implementation
1282 detail, and can be removed or deprecated in future Python releases.
1283 It's recommended to use public APIs from the :mod:`inspect` module
1284 for any introspection needs.
1285
1286
Nick Coghlan367df122013-10-27 01:57:34 +10001287.. _inspect-module-cli:
1288
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001289Command Line Interface
1290----------------------
1291
1292The :mod:`inspect` module also provides a basic introspection capability
1293from the command line.
1294
1295.. program:: inspect
1296
1297By default, accepts the name of a module and prints the source of that
1298module. A class or function within the module can be printed instead by
1299appended a colon and the qualified name of the target object.
1300
1301.. cmdoption:: --details
1302
1303 Print information about the specified object rather than the source code