blob: 850d6018bab1f98890d28749b49fdfd98609c4f6 [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
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080037.. this function name is too big to fit in the ascii-art table below
38.. |coroutine-origin-link| replace:: :func:`sys.set_coroutine_origin_tracking_depth`
39
Xiang Zhanga6902e62017-04-13 10:38:28 +080040+-----------+-------------------+---------------------------+
41| Type | Attribute | Description |
42+===========+===================+===========================+
43| module | __doc__ | documentation string |
44+-----------+-------------------+---------------------------+
45| | __file__ | filename (missing for |
46| | | built-in modules) |
47+-----------+-------------------+---------------------------+
48| class | __doc__ | documentation string |
49+-----------+-------------------+---------------------------+
50| | __name__ | name with which this |
51| | | class was defined |
52+-----------+-------------------+---------------------------+
53| | __qualname__ | qualified name |
54+-----------+-------------------+---------------------------+
55| | __module__ | name of module in which |
56| | | this class was defined |
57+-----------+-------------------+---------------------------+
58| method | __doc__ | documentation string |
59+-----------+-------------------+---------------------------+
60| | __name__ | name with which this |
61| | | method was defined |
62+-----------+-------------------+---------------------------+
63| | __qualname__ | qualified name |
64+-----------+-------------------+---------------------------+
65| | __func__ | function object |
66| | | containing implementation |
67| | | of method |
68+-----------+-------------------+---------------------------+
69| | __self__ | instance to which this |
70| | | method is bound, or |
71| | | ``None`` |
72+-----------+-------------------+---------------------------+
Parth Sharmaf522a6d2019-12-21 00:48:33 +053073| | __module__ | name of module in which |
74| | | this method was defined |
75+-----------+-------------------+---------------------------+
Xiang Zhanga6902e62017-04-13 10:38:28 +080076| function | __doc__ | documentation string |
77+-----------+-------------------+---------------------------+
78| | __name__ | name with which this |
79| | | function was defined |
80+-----------+-------------------+---------------------------+
81| | __qualname__ | qualified name |
82+-----------+-------------------+---------------------------+
83| | __code__ | code object containing |
84| | | compiled function |
85| | | :term:`bytecode` |
86+-----------+-------------------+---------------------------+
87| | __defaults__ | tuple of any default |
88| | | values for positional or |
89| | | keyword parameters |
90+-----------+-------------------+---------------------------+
91| | __kwdefaults__ | mapping of any default |
92| | | values for keyword-only |
93| | | parameters |
94+-----------+-------------------+---------------------------+
95| | __globals__ | global namespace in which |
96| | | this function was defined |
97+-----------+-------------------+---------------------------+
98| | __annotations__ | mapping of parameters |
99| | | names to annotations; |
100| | | ``"return"`` key is |
101| | | reserved for return |
102| | | annotations. |
103+-----------+-------------------+---------------------------+
Parth Sharmaf522a6d2019-12-21 00:48:33 +0530104| | __module__ | name of module in which |
105| | | this function was defined |
106+-----------+-------------------+---------------------------+
Xiang Zhanga6902e62017-04-13 10:38:28 +0800107| traceback | tb_frame | frame object at this |
108| | | level |
109+-----------+-------------------+---------------------------+
110| | tb_lasti | index of last attempted |
111| | | instruction in bytecode |
112+-----------+-------------------+---------------------------+
113| | tb_lineno | current line number in |
114| | | Python source code |
115+-----------+-------------------+---------------------------+
116| | tb_next | next inner traceback |
117| | | object (called by this |
118| | | level) |
119+-----------+-------------------+---------------------------+
120| frame | f_back | next outer frame object |
121| | | (this frame's caller) |
122+-----------+-------------------+---------------------------+
123| | f_builtins | builtins namespace seen |
124| | | by this frame |
125+-----------+-------------------+---------------------------+
126| | f_code | code object being |
127| | | executed in this frame |
128+-----------+-------------------+---------------------------+
129| | f_globals | global namespace seen by |
130| | | this frame |
131+-----------+-------------------+---------------------------+
132| | f_lasti | index of last attempted |
133| | | instruction in bytecode |
134+-----------+-------------------+---------------------------+
135| | f_lineno | current line number in |
136| | | Python source code |
137+-----------+-------------------+---------------------------+
138| | f_locals | local namespace seen by |
139| | | this frame |
140+-----------+-------------------+---------------------------+
Xiang Zhanga6902e62017-04-13 10:38:28 +0800141| | f_trace | tracing function for this |
142| | | frame, or ``None`` |
143+-----------+-------------------+---------------------------+
144| code | co_argcount | number of arguments (not |
145| | | including keyword only |
146| | | arguments, \* or \*\* |
147| | | args) |
148+-----------+-------------------+---------------------------+
149| | co_code | string of raw compiled |
150| | | bytecode |
151+-----------+-------------------+---------------------------+
152| | co_cellvars | tuple of names of cell |
153| | | variables (referenced by |
154| | | containing scopes) |
155+-----------+-------------------+---------------------------+
156| | co_consts | tuple of constants used |
157| | | in the bytecode |
158+-----------+-------------------+---------------------------+
159| | co_filename | name of file in which |
160| | | this code object was |
161| | | created |
162+-----------+-------------------+---------------------------+
163| | co_firstlineno | number of first line in |
164| | | Python source code |
165+-----------+-------------------+---------------------------+
166| | co_flags | bitmap of ``CO_*`` flags, |
167| | | read more :ref:`here |
168| | | <inspect-module-co-flags>`|
169+-----------+-------------------+---------------------------+
170| | co_lnotab | encoded mapping of line |
171| | | numbers to bytecode |
172| | | indices |
173+-----------+-------------------+---------------------------+
174| | co_freevars | tuple of names of free |
175| | | variables (referenced via |
176| | | a function's closure) |
177+-----------+-------------------+---------------------------+
Pablo Galindob76302d2019-05-29 00:45:32 +0100178| | co_posonlyargcount| number of positional only |
179| | | arguments |
180+-----------+-------------------+---------------------------+
Xiang Zhanga6902e62017-04-13 10:38:28 +0800181| | co_kwonlyargcount | number of keyword only |
182| | | arguments (not including |
183| | | \*\* arg) |
184+-----------+-------------------+---------------------------+
185| | co_name | name with which this code |
186| | | object was defined |
187+-----------+-------------------+---------------------------+
188| | co_names | tuple of names of local |
189| | | variables |
190+-----------+-------------------+---------------------------+
191| | co_nlocals | number of local variables |
192+-----------+-------------------+---------------------------+
193| | co_stacksize | virtual machine stack |
194| | | space required |
195+-----------+-------------------+---------------------------+
196| | co_varnames | tuple of names of |
197| | | arguments and local |
198| | | variables |
199+-----------+-------------------+---------------------------+
200| generator | __name__ | name |
201+-----------+-------------------+---------------------------+
202| | __qualname__ | qualified name |
203+-----------+-------------------+---------------------------+
204| | gi_frame | frame |
205+-----------+-------------------+---------------------------+
206| | gi_running | is the generator running? |
207+-----------+-------------------+---------------------------+
208| | gi_code | code |
209+-----------+-------------------+---------------------------+
210| | gi_yieldfrom | object being iterated by |
211| | | ``yield from``, or |
212| | | ``None`` |
213+-----------+-------------------+---------------------------+
214| coroutine | __name__ | name |
215+-----------+-------------------+---------------------------+
216| | __qualname__ | qualified name |
217+-----------+-------------------+---------------------------+
218| | cr_await | object being awaited on, |
219| | | or ``None`` |
220+-----------+-------------------+---------------------------+
221| | cr_frame | frame |
222+-----------+-------------------+---------------------------+
223| | cr_running | is the coroutine running? |
224+-----------+-------------------+---------------------------+
225| | cr_code | code |
226+-----------+-------------------+---------------------------+
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800227| | cr_origin | where coroutine was |
228| | | created, or ``None``. See |
229| | | |coroutine-origin-link| |
230+-----------+-------------------+---------------------------+
Xiang Zhanga6902e62017-04-13 10:38:28 +0800231| builtin | __doc__ | documentation string |
232+-----------+-------------------+---------------------------+
233| | __name__ | original name of this |
234| | | function or method |
235+-----------+-------------------+---------------------------+
236| | __qualname__ | qualified name |
237+-----------+-------------------+---------------------------+
238| | __self__ | instance to which a |
239| | | method is bound, or |
240| | | ``None`` |
241+-----------+-------------------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000242
Victor Stinner40ee3012014-06-16 15:59:28 +0200243.. versionchanged:: 3.5
244
Yury Selivanov5fbad3c2015-08-17 13:04:41 -0400245 Add ``__qualname__`` and ``gi_yieldfrom`` attributes to generators.
246
247 The ``__name__`` attribute of generators is now set from the function
248 name, instead of the code name, and it can now be modified.
Victor Stinner40ee3012014-06-16 15:59:28 +0200249
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800250.. versionchanged:: 3.7
251
252 Add ``cr_origin`` attribute to coroutines.
Georg Brandl116aa622007-08-15 14:28:22 +0000253
254.. function:: getmembers(object[, predicate])
255
Brian Curtindf826f32018-04-26 19:48:26 -0400256 Return all the members of an object in a list of ``(name, value)``
257 pairs sorted by name. If the optional *predicate* argument—which will be
258 called with the ``value`` object of each member—is supplied, only members
259 for which the predicate returns a true value are included.
Georg Brandl116aa622007-08-15 14:28:22 +0000260
Christian Heimes7f044312008-01-06 17:05:40 +0000261 .. note::
262
Ethan Furman63c141c2013-10-18 00:27:39 -0700263 :func:`getmembers` will only return class attributes defined in the
264 metaclass when the argument is a class and those attributes have been
265 listed in the metaclass' custom :meth:`__dir__`.
Christian Heimes7f044312008-01-06 17:05:40 +0000266
Georg Brandl116aa622007-08-15 14:28:22 +0000267
Georg Brandl116aa622007-08-15 14:28:22 +0000268.. function:: getmodulename(path)
269
270 Return the name of the module named by the file *path*, without including the
Nick Coghlan76e07702012-07-18 23:14:57 +1000271 names of enclosing packages. The file extension is checked against all of
272 the entries in :func:`importlib.machinery.all_suffixes`. If it matches,
273 the final path component is returned with the extension removed.
274 Otherwise, ``None`` is returned.
275
276 Note that this function *only* returns a meaningful name for actual
277 Python modules - paths that potentially refer to Python packages will
278 still return ``None``.
279
280 .. versionchanged:: 3.3
Yury Selivanov6dfbc5d2015-07-23 17:49:00 +0300281 The function is based directly on :mod:`importlib`.
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283
284.. function:: ismodule(object)
285
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200286 Return ``True`` if the object is a module.
Georg Brandl116aa622007-08-15 14:28:22 +0000287
288
289.. function:: isclass(object)
290
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200291 Return ``True`` if the object is a class, whether built-in or created in Python
Georg Brandl39cadc32010-10-15 16:53:24 +0000292 code.
Georg Brandl116aa622007-08-15 14:28:22 +0000293
294
295.. function:: ismethod(object)
296
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200297 Return ``True`` if the object is a bound method written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000298
299
300.. function:: isfunction(object)
301
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200302 Return ``True`` if the object is a Python function, which includes functions
Georg Brandl39cadc32010-10-15 16:53:24 +0000303 created by a :term:`lambda` expression.
Georg Brandl116aa622007-08-15 14:28:22 +0000304
305
Christian Heimes7131fd92008-02-19 14:21:46 +0000306.. function:: isgeneratorfunction(object)
307
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200308 Return ``True`` if the object is a Python generator function.
Christian Heimes7131fd92008-02-19 14:21:46 +0000309
Pablo Galindo7cd25432018-10-26 12:19:14 +0100310 .. versionchanged:: 3.8
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200311 Functions wrapped in :func:`functools.partial` now return ``True`` if the
Pablo Galindo7cd25432018-10-26 12:19:14 +0100312 wrapped function is a Python generator function.
313
Christian Heimes7131fd92008-02-19 14:21:46 +0000314
315.. function:: isgenerator(object)
316
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200317 Return ``True`` if the object is a generator.
Christian Heimes7131fd92008-02-19 14:21:46 +0000318
319
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400320.. function:: iscoroutinefunction(object)
321
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200322 Return ``True`` if the object is a :term:`coroutine function`
Yury Selivanov5376ba92015-06-22 12:19:30 -0400323 (a function defined with an :keyword:`async def` syntax).
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400324
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400325 .. versionadded:: 3.5
326
Pablo Galindo7cd25432018-10-26 12:19:14 +0100327 .. versionchanged:: 3.8
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200328 Functions wrapped in :func:`functools.partial` now return ``True`` if the
Pablo Galindo7cd25432018-10-26 12:19:14 +0100329 wrapped function is a :term:`coroutine function`.
330
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400331
332.. function:: iscoroutine(object)
333
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200334 Return ``True`` if the object is a :term:`coroutine` created by an
Yury Selivanov5376ba92015-06-22 12:19:30 -0400335 :keyword:`async def` function.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400336
337 .. versionadded:: 3.5
338
339
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400340.. function:: isawaitable(object)
341
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200342 Return ``True`` if the object can be used in :keyword:`await` expression.
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400343
344 Can also be used to distinguish generator-based coroutines from regular
345 generators::
346
347 def gen():
348 yield
349 @types.coroutine
350 def gen_coro():
351 yield
352
353 assert not isawaitable(gen())
354 assert isawaitable(gen_coro())
355
356 .. versionadded:: 3.5
357
358
Yury Selivanov03660042016-12-15 17:36:05 -0500359.. function:: isasyncgenfunction(object)
360
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200361 Return ``True`` if the object is an :term:`asynchronous generator` function,
Yury Selivanov03660042016-12-15 17:36:05 -0500362 for example::
363
364 >>> async def agen():
365 ... yield 1
366 ...
367 >>> inspect.isasyncgenfunction(agen)
368 True
369
370 .. versionadded:: 3.6
371
Pablo Galindo7cd25432018-10-26 12:19:14 +0100372 .. versionchanged:: 3.8
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200373 Functions wrapped in :func:`functools.partial` now return ``True`` if the
Pablo Galindo7cd25432018-10-26 12:19:14 +0100374 wrapped function is a :term:`asynchronous generator` function.
375
Yury Selivanov03660042016-12-15 17:36:05 -0500376
377.. function:: isasyncgen(object)
378
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200379 Return ``True`` if the object is an :term:`asynchronous generator iterator`
Yury Selivanov03660042016-12-15 17:36:05 -0500380 created by an :term:`asynchronous generator` function.
381
382 .. versionadded:: 3.6
383
Georg Brandl116aa622007-08-15 14:28:22 +0000384.. function:: istraceback(object)
385
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200386 Return ``True`` if the object is a traceback.
Georg Brandl116aa622007-08-15 14:28:22 +0000387
388
389.. function:: isframe(object)
390
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200391 Return ``True`` if the object is a frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000392
393
394.. function:: iscode(object)
395
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200396 Return ``True`` if the object is a code.
Georg Brandl116aa622007-08-15 14:28:22 +0000397
398
399.. function:: isbuiltin(object)
400
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200401 Return ``True`` if the object is a built-in function or a bound built-in method.
Georg Brandl116aa622007-08-15 14:28:22 +0000402
403
404.. function:: isroutine(object)
405
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200406 Return ``True`` if the object is a user-defined or built-in function or method.
Georg Brandl116aa622007-08-15 14:28:22 +0000407
Georg Brandl39cadc32010-10-15 16:53:24 +0000408
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000409.. function:: isabstract(object)
410
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200411 Return ``True`` if the object is an abstract base class.
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000412
Georg Brandl116aa622007-08-15 14:28:22 +0000413
414.. function:: ismethoddescriptor(object)
415
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200416 Return ``True`` if the object is a method descriptor, but not if
Georg Brandl39cadc32010-10-15 16:53:24 +0000417 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
418 are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000419
Georg Brandle6bcc912008-05-12 18:05:20 +0000420 This, for example, is true of ``int.__add__``. An object passing this test
Martin Panterbae5d812016-06-18 03:57:31 +0000421 has a :meth:`~object.__get__` method but not a :meth:`~object.__set__`
422 method, but beyond that the set of attributes varies. A
423 :attr:`~definition.__name__` attribute is usually
Georg Brandle6bcc912008-05-12 18:05:20 +0000424 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000425
Georg Brandl9afde1c2007-11-01 20:32:30 +0000426 Methods implemented via descriptors that also pass one of the other tests
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200427 return ``False`` from the :func:`ismethoddescriptor` test, simply because the
Georg Brandl9afde1c2007-11-01 20:32:30 +0000428 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000429 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000430
431
432.. function:: isdatadescriptor(object)
433
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200434 Return ``True`` if the object is a data descriptor.
Georg Brandl116aa622007-08-15 14:28:22 +0000435
HongWeipeng84f25282019-11-16 05:47:26 +0800436 Data descriptors have a :attr:`~object.__set__` or a :attr:`~object.__delete__` method.
Georg Brandl9afde1c2007-11-01 20:32:30 +0000437 Examples are properties (defined in Python), getsets, and members. The
438 latter two are defined in C and there are more specific tests available for
439 those types, which is robust across Python implementations. Typically, data
Martin Panterbae5d812016-06-18 03:57:31 +0000440 descriptors will also have :attr:`~definition.__name__` and :attr:`__doc__` attributes
Georg Brandl9afde1c2007-11-01 20:32:30 +0000441 (properties, getsets, and members have both of these attributes), but this is
442 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000443
Georg Brandl116aa622007-08-15 14:28:22 +0000444
445.. function:: isgetsetdescriptor(object)
446
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200447 Return ``True`` if the object is a getset descriptor.
Georg Brandl116aa622007-08-15 14:28:22 +0000448
Georg Brandl495f7b52009-10-27 15:28:25 +0000449 .. impl-detail::
450
451 getsets are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000452 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000453 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000454
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456.. function:: ismemberdescriptor(object)
457
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200458 Return ``True`` if the object is a member descriptor.
Georg Brandl116aa622007-08-15 14:28:22 +0000459
Georg Brandl495f7b52009-10-27 15:28:25 +0000460 .. impl-detail::
461
462 Member descriptors are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000463 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000464 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000465
Georg Brandl116aa622007-08-15 14:28:22 +0000466
467.. _inspect-source:
468
469Retrieving source code
470----------------------
471
Georg Brandl116aa622007-08-15 14:28:22 +0000472.. function:: getdoc(object)
473
Georg Brandl0c77a822008-06-10 16:37:50 +0000474 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300475 If the documentation string for an object is not provided and the object is
Serhiy Storchaka08b47c32020-05-18 20:25:07 +0300476 a class, a method, a property or a descriptor, retrieve the documentation
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300477 string from the inheritance hierarchy.
Georg Brandl116aa622007-08-15 14:28:22 +0000478
Berker Peksag4333d8b2015-07-30 18:06:09 +0300479 .. versionchanged:: 3.5
480 Documentation strings are now inherited if not overridden.
481
Georg Brandl116aa622007-08-15 14:28:22 +0000482
483.. function:: getcomments(object)
484
485 Return in a single string any lines of comments immediately preceding the
486 object's source code (for a class, function, or method), or at the top of the
Marco Buttu3f2155f2017-03-17 09:50:23 +0100487 Python source file (if the object is a module). If the object's source code
488 is unavailable, return ``None``. This could happen if the object has been
489 defined in C or the interactive shell.
Georg Brandl116aa622007-08-15 14:28:22 +0000490
491
492.. function:: getfile(object)
493
494 Return the name of the (text or binary) file in which an object was defined.
495 This will fail with a :exc:`TypeError` if the object is a built-in module,
496 class, or function.
497
498
499.. function:: getmodule(object)
500
501 Try to guess which module an object was defined in.
502
503
504.. function:: getsourcefile(object)
505
506 Return the name of the Python source file in which an object was defined. This
507 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
508 function.
509
510
511.. function:: getsourcelines(object)
512
513 Return a list of source lines and starting line number for an object. The
514 argument may be a module, class, method, function, traceback, frame, or code
515 object. The source code is returned as a list of the lines corresponding to the
516 object and the line number indicates where in the original source file the first
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200517 line of code was found. An :exc:`OSError` is raised if the source code cannot
Georg Brandl116aa622007-08-15 14:28:22 +0000518 be retrieved.
519
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200520 .. versionchanged:: 3.3
521 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
522 former.
523
Georg Brandl116aa622007-08-15 14:28:22 +0000524
525.. function:: getsource(object)
526
527 Return the text of the source code for an object. The argument may be a module,
528 class, method, function, traceback, frame, or code object. The source code is
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200529 returned as a single string. An :exc:`OSError` is raised if the source code
Georg Brandl116aa622007-08-15 14:28:22 +0000530 cannot be retrieved.
531
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200532 .. versionchanged:: 3.3
533 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
534 former.
535
Georg Brandl116aa622007-08-15 14:28:22 +0000536
Georg Brandl0c77a822008-06-10 16:37:50 +0000537.. function:: cleandoc(doc)
538
539 Clean up indentation from docstrings that are indented to line up with blocks
Senthil Kumaranebd84e32016-05-29 20:36:58 -0700540 of code.
541
542 All leading whitespace is removed from the first line. Any leading whitespace
543 that can be uniformly removed from the second line onwards is removed. Empty
544 lines at the beginning and end are subsequently removed. Also, all tabs are
545 expanded to spaces.
Georg Brandl0c77a822008-06-10 16:37:50 +0000546
Georg Brandl0c77a822008-06-10 16:37:50 +0000547
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300548.. _inspect-signature-object:
549
Georg Brandle4717722012-08-14 09:45:28 +0200550Introspecting callables with the Signature object
551-------------------------------------------------
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300552
553.. versionadded:: 3.3
554
Georg Brandle4717722012-08-14 09:45:28 +0200555The Signature object represents the call signature of a callable object and its
556return annotation. To retrieve a Signature object, use the :func:`signature`
557function.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300558
Batuhan Taskayaeee1c772020-12-24 01:45:13 +0300559.. function:: signature(callable, *, follow_wrapped=True, globalns=None, localns=None)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300560
Georg Brandle4717722012-08-14 09:45:28 +0200561 Return a :class:`Signature` object for the given ``callable``::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300562
563 >>> from inspect import signature
564 >>> def foo(a, *, b:int, **kwargs):
565 ... pass
566
567 >>> sig = signature(foo)
568
569 >>> str(sig)
570 '(a, *, b:int, **kwargs)'
571
572 >>> str(sig.parameters['b'])
573 'b:int'
574
575 >>> sig.parameters['b'].annotation
576 <class 'int'>
577
Andrés Delfino271818f2018-09-14 14:13:09 -0300578 Accepts a wide range of Python callables, from plain functions and classes to
Georg Brandle4717722012-08-14 09:45:28 +0200579 :func:`functools.partial` objects.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300580
Larry Hastings5c661892014-01-24 06:17:25 -0800581 Raises :exc:`ValueError` if no signature can be provided, and
582 :exc:`TypeError` if that type of object is not supported.
583
Batuhan Taskayaeee1c772020-12-24 01:45:13 +0300584 ``globalns`` and ``localns`` are passed into
585 :func:`typing.get_type_hints` when resolving the annotations.
586
Lysandros Nikolaou1aeeaeb2019-03-10 12:30:11 +0100587 A slash(/) in the signature of a function denotes that the parameters prior
588 to it are positional-only. For more info, see
589 :ref:`the FAQ entry on positional-only parameters <faq-positional-only-arguments>`.
590
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400591 .. versionadded:: 3.5
592 ``follow_wrapped`` parameter. Pass ``False`` to get a signature of
593 ``callable`` specifically (``callable.__wrapped__`` will not be used to
594 unwrap decorated callables.)
595
Batuhan Taskayaeee1c772020-12-24 01:45:13 +0300596 .. versionadded:: 3.10
597 ``globalns`` and ``localns`` parameters.
598
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300599 .. note::
600
Georg Brandle4717722012-08-14 09:45:28 +0200601 Some callables may not be introspectable in certain implementations of
Yury Selivanovd71e52f2014-01-30 00:22:57 -0500602 Python. For example, in CPython, some built-in functions defined in
603 C provide no metadata about their arguments.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300604
Batuhan Taskayaeee1c772020-12-24 01:45:13 +0300605 .. note::
606
607 Will first try to resolve the annotations, but when it fails and
608 encounters with an error while that operation, the annotations will be
609 returned unchanged (as strings).
610
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300611
Andre Delfinodcc997c2020-12-16 22:37:28 -0300612.. class:: Signature(parameters=None, *, return_annotation=Signature.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300613
Georg Brandle4717722012-08-14 09:45:28 +0200614 A Signature object represents the call signature of a function and its return
615 annotation. For each parameter accepted by the function it stores a
616 :class:`Parameter` object in its :attr:`parameters` collection.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300617
Yury Selivanov78356892014-01-30 00:10:54 -0500618 The optional *parameters* argument is a sequence of :class:`Parameter`
619 objects, which is validated to check that there are no parameters with
620 duplicate names, and that the parameters are in the right order, i.e.
621 positional-only first, then positional-or-keyword, and that parameters with
622 defaults follow parameters without defaults.
623
624 The optional *return_annotation* argument, can be an arbitrary Python object,
625 is the "return" annotation of the callable.
626
Georg Brandle4717722012-08-14 09:45:28 +0200627 Signature objects are *immutable*. Use :meth:`Signature.replace` to make a
628 modified copy.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300629
Yury Selivanov67d727e2014-03-29 13:24:14 -0400630 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400631 Signature objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400632
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300633 .. attribute:: Signature.empty
634
635 A special class-level marker to specify absence of a return annotation.
636
637 .. attribute:: Signature.parameters
638
Inada Naoki21105512020-03-02 18:54:49 +0900639 An ordered mapping of parameters' names to the corresponding
640 :class:`Parameter` objects. Parameters appear in strict definition
641 order, including keyword-only parameters.
larryhastingsf36ba122018-01-28 11:13:09 -0800642
643 .. versionchanged:: 3.7
644 Python only explicitly guaranteed that it preserved the declaration
645 order of keyword-only parameters as of version 3.7, although in practice
646 this order had always been preserved in Python 3.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300647
648 .. attribute:: Signature.return_annotation
649
Georg Brandle4717722012-08-14 09:45:28 +0200650 The "return" annotation for the callable. If the callable has no "return"
651 annotation, this attribute is set to :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300652
653 .. method:: Signature.bind(*args, **kwargs)
654
Georg Brandle4717722012-08-14 09:45:28 +0200655 Create a mapping from positional and keyword arguments to parameters.
656 Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
657 signature, or raises a :exc:`TypeError`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300658
659 .. method:: Signature.bind_partial(*args, **kwargs)
660
Georg Brandle4717722012-08-14 09:45:28 +0200661 Works the same way as :meth:`Signature.bind`, but allows the omission of
662 some required arguments (mimics :func:`functools.partial` behavior.)
663 Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
664 passed arguments do not match the signature.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300665
Ezio Melotti8429b672012-09-14 06:35:09 +0300666 .. method:: Signature.replace(*[, parameters][, return_annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300667
Georg Brandle4717722012-08-14 09:45:28 +0200668 Create a new Signature instance based on the instance replace was invoked
669 on. It is possible to pass different ``parameters`` and/or
670 ``return_annotation`` to override the corresponding properties of the base
671 signature. To remove return_annotation from the copied Signature, pass in
672 :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300673
674 ::
675
676 >>> def test(a, b):
677 ... pass
678 >>> sig = signature(test)
679 >>> new_sig = sig.replace(return_annotation="new return anno")
680 >>> str(new_sig)
681 "(a, b) -> 'new return anno'"
682
Batuhan Taskayaeee1c772020-12-24 01:45:13 +0300683 .. classmethod:: Signature.from_callable(obj, *, follow_wrapped=True, globalns=None, localns=None)
Yury Selivanovda396452014-03-27 12:09:24 -0400684
685 Return a :class:`Signature` (or its subclass) object for a given callable
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400686 ``obj``. Pass ``follow_wrapped=False`` to get a signature of ``obj``
Batuhan Taskayaeee1c772020-12-24 01:45:13 +0300687 without unwrapping its ``__wrapped__`` chain. ``globalns`` and
688 ``localns`` will be used as the namespaces when resolving annotations.
Yury Selivanovda396452014-03-27 12:09:24 -0400689
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400690 This method simplifies subclassing of :class:`Signature`::
Yury Selivanovda396452014-03-27 12:09:24 -0400691
692 class MySignature(Signature):
693 pass
694 sig = MySignature.from_callable(min)
695 assert isinstance(sig, MySignature)
696
Yury Selivanov232b9342014-03-29 13:18:30 -0400697 .. versionadded:: 3.5
698
Batuhan Taskayaeee1c772020-12-24 01:45:13 +0300699 .. versionadded:: 3.10
700 ``globalns`` and ``localns`` parameters.
701
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300702
Andre Delfinodcc997c2020-12-16 22:37:28 -0300703.. class:: Parameter(name, kind, *, default=Parameter.empty, annotation=Parameter.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300704
Georg Brandle4717722012-08-14 09:45:28 +0200705 Parameter objects are *immutable*. Instead of modifying a Parameter object,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300706 you can use :meth:`Parameter.replace` to create a modified copy.
707
Yury Selivanov67d727e2014-03-29 13:24:14 -0400708 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400709 Parameter objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400710
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300711 .. attribute:: Parameter.empty
712
Georg Brandle4717722012-08-14 09:45:28 +0200713 A special class-level marker to specify absence of default values and
714 annotations.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300715
716 .. attribute:: Parameter.name
717
Yury Selivanov2393dca2014-01-27 15:07:58 -0500718 The name of the parameter as a string. The name must be a valid
719 Python identifier.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300720
Nick Coghlanb4b966e2016-06-04 14:40:03 -0700721 .. impl-detail::
722
723 CPython generates implicit parameter names of the form ``.0`` on the
724 code objects used to implement comprehensions and generator
725 expressions.
726
727 .. versionchanged:: 3.6
728 These parameter names are exposed by this module as names like
729 ``implicit0``.
730
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300731 .. attribute:: Parameter.default
732
Georg Brandle4717722012-08-14 09:45:28 +0200733 The default value for the parameter. If the parameter has no default
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300734 value, this attribute is set to :attr:`Parameter.empty`.
735
736 .. attribute:: Parameter.annotation
737
Georg Brandle4717722012-08-14 09:45:28 +0200738 The annotation for the parameter. If the parameter has no annotation,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300739 this attribute is set to :attr:`Parameter.empty`.
740
741 .. attribute:: Parameter.kind
742
Georg Brandle4717722012-08-14 09:45:28 +0200743 Describes how argument values are bound to the parameter. Possible values
744 (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300745
Georg Brandl44ea77b2013-03-28 13:28:44 +0100746 .. tabularcolumns:: |l|L|
747
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300748 +------------------------+----------------------------------------------+
749 | Name | Meaning |
750 +========================+==============================================+
751 | *POSITIONAL_ONLY* | Value must be supplied as a positional |
Pablo Galindob76302d2019-05-29 00:45:32 +0100752 | | argument. Positional only parameters are |
753 | | those which appear before a ``/`` entry (if |
754 | | present) in a Python function definition. |
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300755 +------------------------+----------------------------------------------+
756 | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
757 | | positional argument (this is the standard |
758 | | binding behaviour for functions implemented |
759 | | in Python.) |
760 +------------------------+----------------------------------------------+
761 | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
762 | | bound to any other parameter. This |
763 | | corresponds to a ``*args`` parameter in a |
764 | | Python function definition. |
765 +------------------------+----------------------------------------------+
766 | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
767 | | Keyword only parameters are those which |
768 | | appear after a ``*`` or ``*args`` entry in a |
769 | | Python function definition. |
770 +------------------------+----------------------------------------------+
771 | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
772 | | to any other parameter. This corresponds to a|
773 | | ``**kwargs`` parameter in a Python function |
774 | | definition. |
775 +------------------------+----------------------------------------------+
776
Andrew Svetloveed18082012-08-13 18:23:54 +0300777 Example: print all keyword-only arguments without default values::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300778
779 >>> def foo(a, b, *, c, d=10):
780 ... pass
781
782 >>> sig = signature(foo)
783 >>> for param in sig.parameters.values():
784 ... if (param.kind == param.KEYWORD_ONLY and
785 ... param.default is param.empty):
786 ... print('Parameter:', param)
787 Parameter: c
788
Dong-hee Na4aa30062018-06-08 12:46:31 +0900789 .. attribute:: Parameter.kind.description
790
791 Describes a enum value of Parameter.kind.
792
Dong-hee Na4f548672018-06-09 01:07:52 +0900793 .. versionadded:: 3.8
794
Dong-hee Na4aa30062018-06-08 12:46:31 +0900795 Example: print all descriptions of arguments::
796
797 >>> def foo(a, b, *, c, d=10):
798 ... pass
799
800 >>> sig = signature(foo)
801 >>> for param in sig.parameters.values():
802 ... print(param.kind.description)
803 positional or keyword
804 positional or keyword
805 keyword-only
806 keyword-only
807
Ezio Melotti8429b672012-09-14 06:35:09 +0300808 .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300809
Georg Brandle4717722012-08-14 09:45:28 +0200810 Create a new Parameter instance based on the instance replaced was invoked
811 on. To override a :class:`Parameter` attribute, pass the corresponding
812 argument. To remove a default value or/and an annotation from a
813 Parameter, pass :attr:`Parameter.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300814
815 ::
816
817 >>> from inspect import Parameter
818 >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
819 >>> str(param)
820 'foo=42'
821
822 >>> str(param.replace()) # Will create a shallow copy of 'param'
823 'foo=42'
824
825 >>> str(param.replace(default=Parameter.empty, annotation='spam'))
826 "foo:'spam'"
827
Yury Selivanov2393dca2014-01-27 15:07:58 -0500828 .. versionchanged:: 3.4
829 In Python 3.3 Parameter objects were allowed to have ``name`` set
830 to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``.
831 This is no longer permitted.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300832
833.. class:: BoundArguments
834
835 Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
836 Holds the mapping of arguments to the function's parameters.
837
838 .. attribute:: BoundArguments.arguments
839
Inada Naoki21105512020-03-02 18:54:49 +0900840 A mutable mapping of parameters' names to arguments' values.
Rémi Lapeyre2cca8ef2020-01-28 13:47:03 +0100841 Contains only explicitly bound arguments. Changes in :attr:`arguments`
842 will reflect in :attr:`args` and :attr:`kwargs`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300843
Georg Brandle4717722012-08-14 09:45:28 +0200844 Should be used in conjunction with :attr:`Signature.parameters` for any
845 argument processing purposes.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300846
847 .. note::
848
849 Arguments for which :meth:`Signature.bind` or
850 :meth:`Signature.bind_partial` relied on a default value are skipped.
Yury Selivanovb907a512015-05-16 13:45:09 -0400851 However, if needed, use :meth:`BoundArguments.apply_defaults` to add
852 them.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300853
Rémi Lapeyre2cca8ef2020-01-28 13:47:03 +0100854 .. versionchanged:: 3.9
855 :attr:`arguments` is now of type :class:`dict`. Formerly, it was of
856 type :class:`collections.OrderedDict`.
857
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300858 .. attribute:: BoundArguments.args
859
Georg Brandle4717722012-08-14 09:45:28 +0200860 A tuple of positional arguments values. Dynamically computed from the
861 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300862
863 .. attribute:: BoundArguments.kwargs
864
Georg Brandle4717722012-08-14 09:45:28 +0200865 A dict of keyword arguments values. Dynamically computed from the
866 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300867
Yury Selivanov82796192015-05-14 14:14:02 -0400868 .. attribute:: BoundArguments.signature
869
870 A reference to the parent :class:`Signature` object.
871
Yury Selivanovb907a512015-05-16 13:45:09 -0400872 .. method:: BoundArguments.apply_defaults()
873
874 Set default values for missing arguments.
875
876 For variable-positional arguments (``*args``) the default is an
877 empty tuple.
878
879 For variable-keyword arguments (``**kwargs``) the default is an
880 empty dict.
881
882 ::
883
884 >>> def foo(a, b='ham', *args): pass
885 >>> ba = inspect.signature(foo).bind('spam')
886 >>> ba.apply_defaults()
887 >>> ba.arguments
Rémi Lapeyre2cca8ef2020-01-28 13:47:03 +0100888 {'a': 'spam', 'b': 'ham', 'args': ()}
Yury Selivanovb907a512015-05-16 13:45:09 -0400889
Berker Peksag5b3df5b2015-05-16 23:29:31 +0300890 .. versionadded:: 3.5
891
Georg Brandle4717722012-08-14 09:45:28 +0200892 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
893 functions::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300894
895 def test(a, *, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300896 ...
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300897
898 sig = signature(test)
899 ba = sig.bind(10, b=20)
900 test(*ba.args, **ba.kwargs)
901
902
Georg Brandle4717722012-08-14 09:45:28 +0200903.. seealso::
904
905 :pep:`362` - Function Signature Object.
906 The detailed specification, implementation details and examples.
907
908
Georg Brandl116aa622007-08-15 14:28:22 +0000909.. _inspect-classes-functions:
910
911Classes and functions
912---------------------
913
Georg Brandl3dd33882009-06-01 17:35:27 +0000914.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000915
916 Arrange the given list of classes into a hierarchy of nested lists. Where a
917 nested list appears, it contains classes derived from the class whose entry
918 immediately precedes the list. Each entry is a 2-tuple containing a class and a
919 tuple of its base classes. If the *unique* argument is true, exactly one entry
920 appears in the returned structure for each class in the given list. Otherwise,
921 classes using multiple inheritance and their descendants will appear multiple
922 times.
923
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500924
925.. function:: getargspec(func)
926
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000927 Get the names and default values of a Python function's parameters. A
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500928 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000929 returned. *args* is a list of the parameter names. *varargs* and *keywords*
930 are the names of the ``*`` and ``**`` parameters or ``None``. *defaults* is a
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500931 tuple of default argument values or ``None`` if there are no default
932 arguments; if this tuple has *n* elements, they correspond to the last
933 *n* elements listed in *args*.
934
935 .. deprecated:: 3.0
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000936 Use :func:`getfullargspec` for an updated API that is usually a drop-in
937 replacement, but also correctly handles function annotations and
938 keyword-only parameters.
939
940 Alternatively, use :func:`signature` and
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500941 :ref:`Signature Object <inspect-signature-object>`, which provide a
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000942 more structured introspection API for callables.
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500943
944
Georg Brandl138bcb52007-09-12 19:04:21 +0000945.. function:: getfullargspec(func)
946
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000947 Get the names and default values of a Python function's parameters. A
Georg Brandl82402752010-01-09 09:48:46 +0000948 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000949
Georg Brandl3dd33882009-06-01 17:35:27 +0000950 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
951 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000952
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000953 *args* is a list of the positional parameter names.
954 *varargs* is the name of the ``*`` parameter or ``None`` if arbitrary
955 positional arguments are not accepted.
956 *varkw* is the name of the ``**`` parameter or ``None`` if arbitrary
957 keyword arguments are not accepted.
958 *defaults* is an *n*-tuple of default argument values corresponding to the
959 last *n* positional parameters, or ``None`` if there are no such defaults
960 defined.
larryhastingsf36ba122018-01-28 11:13:09 -0800961 *kwonlyargs* is a list of keyword-only parameter names in declaration order.
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000962 *kwonlydefaults* is a dictionary mapping parameter names from *kwonlyargs*
963 to the default values used if no argument is supplied.
964 *annotations* is a dictionary mapping parameter names to annotations.
965 The special key ``"return"`` is used to report the function return value
966 annotation (if any).
967
968 Note that :func:`signature` and
969 :ref:`Signature Object <inspect-signature-object>` provide the recommended
970 API for callable introspection, and support additional behaviours (like
971 positional-only arguments) that are sometimes encountered in extension module
972 APIs. This function is retained primarily for use in code that needs to
973 maintain compatibility with the Python 2 ``inspect`` module API.
Georg Brandl138bcb52007-09-12 19:04:21 +0000974
Nick Coghlan16355782014-03-08 16:36:37 +1000975 .. versionchanged:: 3.4
976 This function is now based on :func:`signature`, but still ignores
977 ``__wrapped__`` attributes and includes the already bound first
978 parameter in the signature output for bound methods.
979
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000980 .. versionchanged:: 3.6
981 This method was previously documented as deprecated in favour of
982 :func:`signature` in Python 3.5, but that decision has been reversed
983 in order to restore a clearly supported standard interface for
984 single-source Python 2/3 code migrating away from the legacy
985 :func:`getargspec` API.
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400986
larryhastingsf36ba122018-01-28 11:13:09 -0800987 .. versionchanged:: 3.7
988 Python only explicitly guaranteed that it preserved the declaration
989 order of keyword-only parameters as of version 3.7, although in practice
990 this order had always been preserved in Python 3.
991
Georg Brandl116aa622007-08-15 14:28:22 +0000992
993.. function:: getargvalues(frame)
994
Georg Brandl3dd33882009-06-01 17:35:27 +0000995 Get information about arguments passed into a particular frame. A
996 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000997 returned. *args* is a list of the argument names. *varargs* and *keywords*
998 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000999 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +00001000
Matthias Bussonnier0899b982017-02-21 21:45:51 -08001001 .. note::
1002 This function was inadvertently marked as deprecated in Python 3.5.
Yury Selivanov945fff42015-05-22 16:28:05 -04001003
Georg Brandl116aa622007-08-15 14:28:22 +00001004
Andrew Svetlov735d3172012-10-27 00:28:20 +03001005.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Georg Brandl116aa622007-08-15 14:28:22 +00001006
Michael Foord3af125a2012-04-21 18:22:28 +01001007 Format a pretty argument spec from the values returned by
Berker Peksagfa3922c2015-07-31 04:11:29 +03001008 :func:`getfullargspec`.
Michael Foord3af125a2012-04-21 18:22:28 +01001009
1010 The first seven arguments are (``args``, ``varargs``, ``varkw``,
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001011 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
Andrew Svetlov735d3172012-10-27 00:28:20 +03001012
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001013 The other six arguments are functions that are called to turn argument names,
1014 ``*`` argument name, ``**`` argument name, default values, return annotation
1015 and individual annotations into strings, respectively.
1016
1017 For example:
1018
1019 >>> from inspect import formatargspec, getfullargspec
1020 >>> def f(a: int, b: float):
1021 ... pass
1022 ...
1023 >>> formatargspec(*getfullargspec(f))
1024 '(a: int, b: float)'
Georg Brandl116aa622007-08-15 14:28:22 +00001025
Yury Selivanov945fff42015-05-22 16:28:05 -04001026 .. deprecated:: 3.5
1027 Use :func:`signature` and
1028 :ref:`Signature Object <inspect-signature-object>`, which provide a
1029 better introspecting API for callables.
1030
Georg Brandl116aa622007-08-15 14:28:22 +00001031
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001032.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +00001033
1034 Format a pretty argument spec from the four values returned by
1035 :func:`getargvalues`. The format\* arguments are the corresponding optional
1036 formatting functions that are called to turn names and values into strings.
1037
Matthias Bussonnier0899b982017-02-21 21:45:51 -08001038 .. note::
1039 This function was inadvertently marked as deprecated in Python 3.5.
Yury Selivanov945fff42015-05-22 16:28:05 -04001040
Georg Brandl116aa622007-08-15 14:28:22 +00001041
1042.. function:: getmro(cls)
1043
1044 Return a tuple of class cls's base classes, including cls, in method resolution
1045 order. No class appears more than once in this tuple. Note that the method
1046 resolution order depends on cls's type. Unless a very peculiar user-defined
1047 metatype is in use, cls will be the first element of the tuple.
1048
1049
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001050.. function:: getcallargs(func, /, *args, **kwds)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001051
1052 Bind the *args* and *kwds* to the argument names of the Python function or
1053 method *func*, as if it was called with them. For bound methods, bind also the
1054 first argument (typically named ``self``) to the associated instance. A dict
1055 is returned, mapping the argument names (including the names of the ``*`` and
1056 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
1057 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
1058 an exception because of incompatible signature, an exception of the same type
1059 and the same or similar message is raised. For example::
1060
1061 >>> from inspect import getcallargs
1062 >>> def f(a, b=1, *pos, **named):
1063 ... pass
Andrew Svetlove939f382012-08-09 13:25:32 +03001064 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
1065 True
1066 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
1067 True
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001068 >>> getcallargs(f)
1069 Traceback (most recent call last):
1070 ...
Andrew Svetlove939f382012-08-09 13:25:32 +03001071 TypeError: f() missing 1 required positional argument: 'a'
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001072
1073 .. versionadded:: 3.2
1074
Yury Selivanov3cfec2e2015-05-22 11:38:38 -04001075 .. deprecated:: 3.5
1076 Use :meth:`Signature.bind` and :meth:`Signature.bind_partial` instead.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +03001077
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001078
Nick Coghlan2f92e542012-06-23 19:39:55 +10001079.. function:: getclosurevars(func)
1080
1081 Get the mapping of external name references in a Python function or
1082 method *func* to their current values. A
1083 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
1084 is returned. *nonlocals* maps referenced names to lexical closure
1085 variables, *globals* to the function's module globals and *builtins* to
1086 the builtins visible from the function body. *unbound* is the set of names
1087 referenced in the function that could not be resolved at all given the
1088 current module globals and builtins.
1089
1090 :exc:`TypeError` is raised if *func* is not a Python function or method.
1091
1092 .. versionadded:: 3.3
1093
1094
Nick Coghlane8c45d62013-07-28 20:00:01 +10001095.. function:: unwrap(func, *, stop=None)
1096
1097 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
1098 attributes returning the last object in the chain.
1099
1100 *stop* is an optional callback accepting an object in the wrapper chain
1101 as its sole argument that allows the unwrapping to be terminated early if
1102 the callback returns a true value. If the callback never returns a true
1103 value, the last object in the chain is returned as usual. For example,
1104 :func:`signature` uses this to stop unwrapping if any object in the
1105 chain has a ``__signature__`` attribute defined.
1106
1107 :exc:`ValueError` is raised if a cycle is encountered.
1108
1109 .. versionadded:: 3.4
1110
1111
Georg Brandl116aa622007-08-15 14:28:22 +00001112.. _inspect-stack:
1113
1114The interpreter stack
1115---------------------
1116
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001117When the following functions return "frame records," each record is a
1118:term:`named tuple`
1119``FrameInfo(frame, filename, lineno, function, code_context, index)``.
1120The tuple contains the frame object, the filename, the line number of the
1121current line,
Georg Brandl116aa622007-08-15 14:28:22 +00001122the function name, a list of lines of context from the source code, and the
1123index of the current line within that list.
1124
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001125.. versionchanged:: 3.5
1126 Return a named tuple instead of a tuple.
1127
Georg Brandle720c0a2009-04-27 16:20:50 +00001128.. note::
Georg Brandl116aa622007-08-15 14:28:22 +00001129
1130 Keeping references to frame objects, as found in the first element of the frame
1131 records these functions return, can cause your program to create reference
1132 cycles. Once a reference cycle has been created, the lifespan of all objects
1133 which can be accessed from the objects which form the cycle can become much
1134 longer even if Python's optional cycle detector is enabled. If such cycles must
1135 be created, it is important to ensure they are explicitly broken to avoid the
1136 delayed destruction of objects and increased memory consumption which occurs.
1137
1138 Though the cycle detector will catch these, destruction of the frames (and local
1139 variables) can be made deterministic by removing the cycle in a
1140 :keyword:`finally` clause. This is also important if the cycle detector was
1141 disabled when Python was compiled or using :func:`gc.disable`. For example::
1142
1143 def handle_stackframe_without_leak():
1144 frame = inspect.currentframe()
1145 try:
1146 # do something with the frame
1147 finally:
1148 del frame
1149
Antoine Pitrou58720d62013-08-05 23:26:40 +02001150 If you want to keep the frame around (for example to print a traceback
1151 later), you can also break reference cycles by using the
1152 :meth:`frame.clear` method.
1153
Georg Brandl116aa622007-08-15 14:28:22 +00001154The optional *context* argument supported by most of these functions specifies
1155the number of lines of context to return, which are centered around the current
1156line.
1157
1158
Georg Brandl3dd33882009-06-01 17:35:27 +00001159.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001160
Georg Brandl48310cd2009-01-03 21:18:54 +00001161 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +00001162 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +00001163
1164
Georg Brandl3dd33882009-06-01 17:35:27 +00001165.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001166
1167 Get a list of frame records for a frame and all outer frames. These frames
1168 represent the calls that lead to the creation of *frame*. The first entry in the
1169 returned list represents *frame*; the last entry represents the outermost call
1170 on *frame*'s stack.
1171
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001172 .. versionchanged:: 3.5
1173 A list of :term:`named tuples <named tuple>`
1174 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1175 is returned.
1176
Georg Brandl116aa622007-08-15 14:28:22 +00001177
Georg Brandl3dd33882009-06-01 17:35:27 +00001178.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001179
1180 Get a list of frame records for a traceback's frame and all inner frames. These
1181 frames represent calls made as a consequence of *frame*. The first entry in the
1182 list represents *traceback*; the last entry represents where the exception was
1183 raised.
1184
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001185 .. versionchanged:: 3.5
1186 A list of :term:`named tuples <named tuple>`
1187 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1188 is returned.
1189
Georg Brandl116aa622007-08-15 14:28:22 +00001190
1191.. function:: currentframe()
1192
1193 Return the frame object for the caller's stack frame.
1194
Georg Brandl495f7b52009-10-27 15:28:25 +00001195 .. impl-detail::
1196
1197 This function relies on Python stack frame support in the interpreter,
1198 which isn't guaranteed to exist in all implementations of Python. If
1199 running in an implementation without Python stack frame support this
1200 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001201
Georg Brandl116aa622007-08-15 14:28:22 +00001202
Georg Brandl3dd33882009-06-01 17:35:27 +00001203.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001204
1205 Return a list of frame records for the caller's stack. The first entry in the
1206 returned list represents the caller; the last entry represents the outermost
1207 call on the stack.
1208
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001209 .. versionchanged:: 3.5
1210 A list of :term:`named tuples <named tuple>`
1211 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1212 is returned.
1213
Georg Brandl116aa622007-08-15 14:28:22 +00001214
Georg Brandl3dd33882009-06-01 17:35:27 +00001215.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001216
1217 Return a list of frame records for the stack between the current frame and the
1218 frame in which an exception currently being handled was raised in. The first
1219 entry in the list represents the caller; the last entry represents where the
1220 exception was raised.
1221
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001222 .. versionchanged:: 3.5
1223 A list of :term:`named tuples <named tuple>`
1224 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1225 is returned.
1226
Michael Foord95fc51d2010-11-20 15:07:30 +00001227
1228Fetching attributes statically
1229------------------------------
1230
1231Both :func:`getattr` and :func:`hasattr` can trigger code execution when
1232fetching or checking for the existence of attributes. Descriptors, like
1233properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
1234may be called.
1235
1236For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +02001237can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +00001238but avoids executing code when it fetches attributes.
1239
1240.. function:: getattr_static(obj, attr, default=None)
1241
1242 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +02001243 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +00001244
1245 Note: this function may not be able to retrieve all attributes
1246 that getattr can fetch (like dynamically created attributes)
1247 and may find attributes that getattr can't (like descriptors
1248 that raise AttributeError). It can also return descriptors objects
1249 instead of instance members.
1250
Serhiy Storchakabfdcd432013-10-13 23:09:14 +03001251 If the instance :attr:`~object.__dict__` is shadowed by another member (for
1252 example a property) then this function will be unable to find instance
1253 members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001254
Michael Foorddcebe0f2011-03-15 19:20:44 -04001255 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +00001256
Éric Araujo941afed2011-09-01 02:47:34 +02001257:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +00001258getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +00001259is returned instead of the underlying attribute.
1260
1261You can handle these with code like the following. Note that
1262for arbitrary getset descriptors invoking these may trigger
1263code execution::
1264
1265 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +00001266 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +00001267 __slots__ = ['foo']
1268
1269 slot_descriptor = type(_foo.foo)
1270 getset_descriptor = type(type(open(__file__)).name)
1271 wrapper_descriptor = type(str.__dict__['__add__'])
1272 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
1273
1274 result = getattr_static(some_object, 'foo')
1275 if type(result) in descriptor_types:
1276 try:
1277 result = result.__get__()
1278 except AttributeError:
1279 # descriptors can raise AttributeError to
1280 # indicate there is no underlying value
1281 # in which case the descriptor itself will
1282 # have to do
1283 pass
Nick Coghlane0f04652010-11-21 03:44:04 +00001284
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001285
Yury Selivanov5376ba92015-06-22 12:19:30 -04001286Current State of Generators and Coroutines
1287------------------------------------------
Nick Coghlane0f04652010-11-21 03:44:04 +00001288
1289When implementing coroutine schedulers and for other advanced uses of
1290generators, it is useful to determine whether a generator is currently
1291executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001292terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +00001293generator to be determined easily.
1294
1295.. function:: getgeneratorstate(generator)
1296
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001297 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +00001298
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001299 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +00001300 * GEN_CREATED: Waiting to start execution.
1301 * GEN_RUNNING: Currently being executed by the interpreter.
1302 * GEN_SUSPENDED: Currently suspended at a yield expression.
1303 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +00001304
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001305 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001306
Yury Selivanov5376ba92015-06-22 12:19:30 -04001307.. function:: getcoroutinestate(coroutine)
1308
1309 Get current state of a coroutine object. The function is intended to be
1310 used with coroutine objects created by :keyword:`async def` functions, but
1311 will accept any coroutine-like object that has ``cr_running`` and
1312 ``cr_frame`` attributes.
1313
1314 Possible states are:
1315 * CORO_CREATED: Waiting to start execution.
1316 * CORO_RUNNING: Currently being executed by the interpreter.
1317 * CORO_SUSPENDED: Currently suspended at an await expression.
1318 * CORO_CLOSED: Execution has completed.
1319
1320 .. versionadded:: 3.5
1321
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001322The current internal state of the generator can also be queried. This is
1323mostly useful for testing purposes, to ensure that internal state is being
1324updated as expected:
1325
1326.. function:: getgeneratorlocals(generator)
1327
1328 Get the mapping of live local variables in *generator* to their current
1329 values. A dictionary is returned that maps from variable names to values.
1330 This is the equivalent of calling :func:`locals` in the body of the
1331 generator, and all the same caveats apply.
1332
1333 If *generator* is a :term:`generator` with no currently associated frame,
1334 then an empty dictionary is returned. :exc:`TypeError` is raised if
1335 *generator* is not a Python generator object.
1336
1337 .. impl-detail::
1338
1339 This function relies on the generator exposing a Python stack frame
1340 for introspection, which isn't guaranteed to be the case in all
1341 implementations of Python. In such cases, this function will always
1342 return an empty dictionary.
1343
1344 .. versionadded:: 3.3
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001345
Yury Selivanov5376ba92015-06-22 12:19:30 -04001346.. function:: getcoroutinelocals(coroutine)
1347
1348 This function is analogous to :func:`~inspect.getgeneratorlocals`, but
1349 works for coroutine objects created by :keyword:`async def` functions.
1350
1351 .. versionadded:: 3.5
1352
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001353
Yury Selivanovea75a512016-10-20 13:06:30 -04001354.. _inspect-module-co-flags:
1355
1356Code Objects Bit Flags
1357----------------------
1358
1359Python code objects have a ``co_flags`` attribute, which is a bitmap of
1360the following flags:
1361
Xiang Zhanga6902e62017-04-13 10:38:28 +08001362.. data:: CO_OPTIMIZED
1363
1364 The code object is optimized, using fast locals.
1365
Yury Selivanovea75a512016-10-20 13:06:30 -04001366.. data:: CO_NEWLOCALS
1367
1368 If set, a new dict will be created for the frame's ``f_locals`` when
1369 the code object is executed.
1370
1371.. data:: CO_VARARGS
1372
1373 The code object has a variable positional parameter (``*args``-like).
1374
1375.. data:: CO_VARKEYWORDS
1376
1377 The code object has a variable keyword parameter (``**kwargs``-like).
1378
Xiang Zhanga6902e62017-04-13 10:38:28 +08001379.. data:: CO_NESTED
1380
1381 The flag is set when the code object is a nested function.
1382
Yury Selivanovea75a512016-10-20 13:06:30 -04001383.. data:: CO_GENERATOR
1384
1385 The flag is set when the code object is a generator function, i.e.
1386 a generator object is returned when the code object is executed.
1387
1388.. data:: CO_NOFREE
1389
1390 The flag is set if there are no free or cell variables.
1391
1392.. data:: CO_COROUTINE
1393
Yury Selivanovb738a1f2016-10-20 16:30:51 -04001394 The flag is set when the code object is a coroutine function.
1395 When the code object is executed it returns a coroutine object.
1396 See :pep:`492` for more details.
Yury Selivanovea75a512016-10-20 13:06:30 -04001397
1398 .. versionadded:: 3.5
1399
1400.. data:: CO_ITERABLE_COROUTINE
1401
Yury Selivanovb738a1f2016-10-20 16:30:51 -04001402 The flag is used to transform generators into generator-based
1403 coroutines. Generator objects with this flag can be used in
1404 ``await`` expression, and can ``yield from`` coroutine objects.
1405 See :pep:`492` for more details.
Yury Selivanovea75a512016-10-20 13:06:30 -04001406
1407 .. versionadded:: 3.5
1408
Yury Selivanove20fed92016-10-20 13:11:34 -04001409.. data:: CO_ASYNC_GENERATOR
1410
Yury Selivanovb738a1f2016-10-20 16:30:51 -04001411 The flag is set when the code object is an asynchronous generator
1412 function. When the code object is executed it returns an
1413 asynchronous generator object. See :pep:`525` for more details.
Yury Selivanove20fed92016-10-20 13:11:34 -04001414
1415 .. versionadded:: 3.6
1416
Yury Selivanovea75a512016-10-20 13:06:30 -04001417.. note::
1418 The flags are specific to CPython, and may not be defined in other
1419 Python implementations. Furthermore, the flags are an implementation
1420 detail, and can be removed or deprecated in future Python releases.
1421 It's recommended to use public APIs from the :mod:`inspect` module
1422 for any introspection needs.
1423
1424
Nick Coghlan367df122013-10-27 01:57:34 +10001425.. _inspect-module-cli:
1426
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001427Command Line Interface
1428----------------------
1429
1430The :mod:`inspect` module also provides a basic introspection capability
1431from the command line.
1432
1433.. program:: inspect
1434
1435By default, accepts the name of a module and prints the source of that
1436module. A class or function within the module can be printed instead by
1437appended a colon and the qualified name of the target object.
1438
1439.. cmdoption:: --details
1440
1441 Print information about the specified object rather than the source code