blob: 10339641c3b4350e06a7cb53082e60d8914881bb [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+-----------+-------------------+---------------------------+
Victor Stinnera3c3ffa2021-02-18 12:35:37 +010098| | __builtins__ | builtins namespace |
99+-----------+-------------------+---------------------------+
Xiang Zhanga6902e62017-04-13 10:38:28 +0800100| | __annotations__ | mapping of parameters |
101| | | names to annotations; |
102| | | ``"return"`` key is |
103| | | reserved for return |
104| | | annotations. |
105+-----------+-------------------+---------------------------+
Parth Sharmaf522a6d2019-12-21 00:48:33 +0530106| | __module__ | name of module in which |
107| | | this function was defined |
108+-----------+-------------------+---------------------------+
Xiang Zhanga6902e62017-04-13 10:38:28 +0800109| traceback | tb_frame | frame object at this |
110| | | level |
111+-----------+-------------------+---------------------------+
112| | tb_lasti | index of last attempted |
113| | | instruction in bytecode |
114+-----------+-------------------+---------------------------+
115| | tb_lineno | current line number in |
116| | | Python source code |
117+-----------+-------------------+---------------------------+
118| | tb_next | next inner traceback |
119| | | object (called by this |
120| | | level) |
121+-----------+-------------------+---------------------------+
122| frame | f_back | next outer frame object |
123| | | (this frame's caller) |
124+-----------+-------------------+---------------------------+
125| | f_builtins | builtins namespace seen |
126| | | by this frame |
127+-----------+-------------------+---------------------------+
128| | f_code | code object being |
129| | | executed in this frame |
130+-----------+-------------------+---------------------------+
131| | f_globals | global namespace seen by |
132| | | this frame |
133+-----------+-------------------+---------------------------+
134| | f_lasti | index of last attempted |
135| | | instruction in bytecode |
136+-----------+-------------------+---------------------------+
137| | f_lineno | current line number in |
138| | | Python source code |
139+-----------+-------------------+---------------------------+
140| | f_locals | local namespace seen by |
141| | | this frame |
142+-----------+-------------------+---------------------------+
Xiang Zhanga6902e62017-04-13 10:38:28 +0800143| | f_trace | tracing function for this |
144| | | frame, or ``None`` |
145+-----------+-------------------+---------------------------+
146| code | co_argcount | number of arguments (not |
147| | | including keyword only |
148| | | arguments, \* or \*\* |
149| | | args) |
150+-----------+-------------------+---------------------------+
151| | co_code | string of raw compiled |
152| | | bytecode |
153+-----------+-------------------+---------------------------+
154| | co_cellvars | tuple of names of cell |
155| | | variables (referenced by |
156| | | containing scopes) |
157+-----------+-------------------+---------------------------+
158| | co_consts | tuple of constants used |
159| | | in the bytecode |
160+-----------+-------------------+---------------------------+
161| | co_filename | name of file in which |
162| | | this code object was |
163| | | created |
164+-----------+-------------------+---------------------------+
165| | co_firstlineno | number of first line in |
166| | | Python source code |
167+-----------+-------------------+---------------------------+
168| | co_flags | bitmap of ``CO_*`` flags, |
169| | | read more :ref:`here |
170| | | <inspect-module-co-flags>`|
171+-----------+-------------------+---------------------------+
172| | co_lnotab | encoded mapping of line |
173| | | numbers to bytecode |
174| | | indices |
175+-----------+-------------------+---------------------------+
176| | co_freevars | tuple of names of free |
177| | | variables (referenced via |
178| | | a function's closure) |
179+-----------+-------------------+---------------------------+
Pablo Galindob76302d2019-05-29 00:45:32 +0100180| | co_posonlyargcount| number of positional only |
181| | | arguments |
182+-----------+-------------------+---------------------------+
Xiang Zhanga6902e62017-04-13 10:38:28 +0800183| | co_kwonlyargcount | number of keyword only |
184| | | arguments (not including |
185| | | \*\* arg) |
186+-----------+-------------------+---------------------------+
187| | co_name | name with which this code |
188| | | object was defined |
189+-----------+-------------------+---------------------------+
190| | co_names | tuple of names of local |
191| | | variables |
192+-----------+-------------------+---------------------------+
193| | co_nlocals | number of local variables |
194+-----------+-------------------+---------------------------+
195| | co_stacksize | virtual machine stack |
196| | | space required |
197+-----------+-------------------+---------------------------+
198| | co_varnames | tuple of names of |
199| | | arguments and local |
200| | | variables |
201+-----------+-------------------+---------------------------+
202| generator | __name__ | name |
203+-----------+-------------------+---------------------------+
204| | __qualname__ | qualified name |
205+-----------+-------------------+---------------------------+
206| | gi_frame | frame |
207+-----------+-------------------+---------------------------+
208| | gi_running | is the generator running? |
209+-----------+-------------------+---------------------------+
210| | gi_code | code |
211+-----------+-------------------+---------------------------+
212| | gi_yieldfrom | object being iterated by |
213| | | ``yield from``, or |
214| | | ``None`` |
215+-----------+-------------------+---------------------------+
216| coroutine | __name__ | name |
217+-----------+-------------------+---------------------------+
218| | __qualname__ | qualified name |
219+-----------+-------------------+---------------------------+
220| | cr_await | object being awaited on, |
221| | | or ``None`` |
222+-----------+-------------------+---------------------------+
223| | cr_frame | frame |
224+-----------+-------------------+---------------------------+
225| | cr_running | is the coroutine running? |
226+-----------+-------------------+---------------------------+
227| | cr_code | code |
228+-----------+-------------------+---------------------------+
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800229| | cr_origin | where coroutine was |
230| | | created, or ``None``. See |
231| | | |coroutine-origin-link| |
232+-----------+-------------------+---------------------------+
Xiang Zhanga6902e62017-04-13 10:38:28 +0800233| builtin | __doc__ | documentation string |
234+-----------+-------------------+---------------------------+
235| | __name__ | original name of this |
236| | | function or method |
237+-----------+-------------------+---------------------------+
238| | __qualname__ | qualified name |
239+-----------+-------------------+---------------------------+
240| | __self__ | instance to which a |
241| | | method is bound, or |
242| | | ``None`` |
243+-----------+-------------------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000244
Victor Stinner40ee3012014-06-16 15:59:28 +0200245.. versionchanged:: 3.5
246
Yury Selivanov5fbad3c2015-08-17 13:04:41 -0400247 Add ``__qualname__`` and ``gi_yieldfrom`` attributes to generators.
248
249 The ``__name__`` attribute of generators is now set from the function
250 name, instead of the code name, and it can now be modified.
Victor Stinner40ee3012014-06-16 15:59:28 +0200251
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800252.. versionchanged:: 3.7
253
254 Add ``cr_origin`` attribute to coroutines.
Georg Brandl116aa622007-08-15 14:28:22 +0000255
Victor Stinnera3c3ffa2021-02-18 12:35:37 +0100256.. versionchanged:: 3.10
257
258 Add ``__builtins__`` attribute to functions.
259
Georg Brandl116aa622007-08-15 14:28:22 +0000260.. function:: getmembers(object[, predicate])
261
Brian Curtindf826f32018-04-26 19:48:26 -0400262 Return all the members of an object in a list of ``(name, value)``
263 pairs sorted by name. If the optional *predicate* argument—which will be
264 called with the ``value`` object of each member—is supplied, only members
265 for which the predicate returns a true value are included.
Georg Brandl116aa622007-08-15 14:28:22 +0000266
Christian Heimes7f044312008-01-06 17:05:40 +0000267 .. note::
268
Ethan Furman63c141c2013-10-18 00:27:39 -0700269 :func:`getmembers` will only return class attributes defined in the
270 metaclass when the argument is a class and those attributes have been
271 listed in the metaclass' custom :meth:`__dir__`.
Christian Heimes7f044312008-01-06 17:05:40 +0000272
Georg Brandl116aa622007-08-15 14:28:22 +0000273
Georg Brandl116aa622007-08-15 14:28:22 +0000274.. function:: getmodulename(path)
275
276 Return the name of the module named by the file *path*, without including the
Nick Coghlan76e07702012-07-18 23:14:57 +1000277 names of enclosing packages. The file extension is checked against all of
278 the entries in :func:`importlib.machinery.all_suffixes`. If it matches,
279 the final path component is returned with the extension removed.
280 Otherwise, ``None`` is returned.
281
282 Note that this function *only* returns a meaningful name for actual
283 Python modules - paths that potentially refer to Python packages will
284 still return ``None``.
285
286 .. versionchanged:: 3.3
Yury Selivanov6dfbc5d2015-07-23 17:49:00 +0300287 The function is based directly on :mod:`importlib`.
Georg Brandl116aa622007-08-15 14:28:22 +0000288
289
290.. function:: ismodule(object)
291
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200292 Return ``True`` if the object is a module.
Georg Brandl116aa622007-08-15 14:28:22 +0000293
294
295.. function:: isclass(object)
296
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200297 Return ``True`` if the object is a class, whether built-in or created in Python
Georg Brandl39cadc32010-10-15 16:53:24 +0000298 code.
Georg Brandl116aa622007-08-15 14:28:22 +0000299
300
301.. function:: ismethod(object)
302
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200303 Return ``True`` if the object is a bound method written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000304
305
306.. function:: isfunction(object)
307
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200308 Return ``True`` if the object is a Python function, which includes functions
Georg Brandl39cadc32010-10-15 16:53:24 +0000309 created by a :term:`lambda` expression.
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311
Christian Heimes7131fd92008-02-19 14:21:46 +0000312.. function:: isgeneratorfunction(object)
313
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200314 Return ``True`` if the object is a Python generator function.
Christian Heimes7131fd92008-02-19 14:21:46 +0000315
Pablo Galindo7cd25432018-10-26 12:19:14 +0100316 .. versionchanged:: 3.8
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200317 Functions wrapped in :func:`functools.partial` now return ``True`` if the
Pablo Galindo7cd25432018-10-26 12:19:14 +0100318 wrapped function is a Python generator function.
319
Christian Heimes7131fd92008-02-19 14:21:46 +0000320
321.. function:: isgenerator(object)
322
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200323 Return ``True`` if the object is a generator.
Christian Heimes7131fd92008-02-19 14:21:46 +0000324
325
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400326.. function:: iscoroutinefunction(object)
327
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200328 Return ``True`` if the object is a :term:`coroutine function`
Yury Selivanov5376ba92015-06-22 12:19:30 -0400329 (a function defined with an :keyword:`async def` syntax).
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400330
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400331 .. versionadded:: 3.5
332
Pablo Galindo7cd25432018-10-26 12:19:14 +0100333 .. versionchanged:: 3.8
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200334 Functions wrapped in :func:`functools.partial` now return ``True`` if the
Pablo Galindo7cd25432018-10-26 12:19:14 +0100335 wrapped function is a :term:`coroutine function`.
336
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400337
338.. function:: iscoroutine(object)
339
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200340 Return ``True`` if the object is a :term:`coroutine` created by an
Yury Selivanov5376ba92015-06-22 12:19:30 -0400341 :keyword:`async def` function.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400342
343 .. versionadded:: 3.5
344
345
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400346.. function:: isawaitable(object)
347
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200348 Return ``True`` if the object can be used in :keyword:`await` expression.
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400349
350 Can also be used to distinguish generator-based coroutines from regular
351 generators::
352
353 def gen():
354 yield
355 @types.coroutine
356 def gen_coro():
357 yield
358
359 assert not isawaitable(gen())
360 assert isawaitable(gen_coro())
361
362 .. versionadded:: 3.5
363
364
Yury Selivanov03660042016-12-15 17:36:05 -0500365.. function:: isasyncgenfunction(object)
366
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200367 Return ``True`` if the object is an :term:`asynchronous generator` function,
Yury Selivanov03660042016-12-15 17:36:05 -0500368 for example::
369
370 >>> async def agen():
371 ... yield 1
372 ...
373 >>> inspect.isasyncgenfunction(agen)
374 True
375
376 .. versionadded:: 3.6
377
Pablo Galindo7cd25432018-10-26 12:19:14 +0100378 .. versionchanged:: 3.8
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200379 Functions wrapped in :func:`functools.partial` now return ``True`` if the
Pablo Galindo7cd25432018-10-26 12:19:14 +0100380 wrapped function is a :term:`asynchronous generator` function.
381
Yury Selivanov03660042016-12-15 17:36:05 -0500382
383.. function:: isasyncgen(object)
384
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200385 Return ``True`` if the object is an :term:`asynchronous generator iterator`
Yury Selivanov03660042016-12-15 17:36:05 -0500386 created by an :term:`asynchronous generator` function.
387
388 .. versionadded:: 3.6
389
Georg Brandl116aa622007-08-15 14:28:22 +0000390.. function:: istraceback(object)
391
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200392 Return ``True`` if the object is a traceback.
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394
395.. function:: isframe(object)
396
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200397 Return ``True`` if the object is a frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399
400.. function:: iscode(object)
401
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200402 Return ``True`` if the object is a code.
Georg Brandl116aa622007-08-15 14:28:22 +0000403
404
405.. function:: isbuiltin(object)
406
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200407 Return ``True`` if the object is a built-in function or a bound built-in method.
Georg Brandl116aa622007-08-15 14:28:22 +0000408
409
410.. function:: isroutine(object)
411
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200412 Return ``True`` if the object is a user-defined or built-in function or method.
Georg Brandl116aa622007-08-15 14:28:22 +0000413
Georg Brandl39cadc32010-10-15 16:53:24 +0000414
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000415.. function:: isabstract(object)
416
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200417 Return ``True`` if the object is an abstract base class.
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000418
Georg Brandl116aa622007-08-15 14:28:22 +0000419
420.. function:: ismethoddescriptor(object)
421
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200422 Return ``True`` if the object is a method descriptor, but not if
Georg Brandl39cadc32010-10-15 16:53:24 +0000423 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
424 are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000425
Georg Brandle6bcc912008-05-12 18:05:20 +0000426 This, for example, is true of ``int.__add__``. An object passing this test
Martin Panterbae5d812016-06-18 03:57:31 +0000427 has a :meth:`~object.__get__` method but not a :meth:`~object.__set__`
428 method, but beyond that the set of attributes varies. A
429 :attr:`~definition.__name__` attribute is usually
Georg Brandle6bcc912008-05-12 18:05:20 +0000430 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000431
Georg Brandl9afde1c2007-11-01 20:32:30 +0000432 Methods implemented via descriptors that also pass one of the other tests
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200433 return ``False`` from the :func:`ismethoddescriptor` test, simply because the
Georg Brandl9afde1c2007-11-01 20:32:30 +0000434 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000435 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000436
437
438.. function:: isdatadescriptor(object)
439
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200440 Return ``True`` if the object is a data descriptor.
Georg Brandl116aa622007-08-15 14:28:22 +0000441
HongWeipeng84f25282019-11-16 05:47:26 +0800442 Data descriptors have a :attr:`~object.__set__` or a :attr:`~object.__delete__` method.
Georg Brandl9afde1c2007-11-01 20:32:30 +0000443 Examples are properties (defined in Python), getsets, and members. The
444 latter two are defined in C and there are more specific tests available for
445 those types, which is robust across Python implementations. Typically, data
Martin Panterbae5d812016-06-18 03:57:31 +0000446 descriptors will also have :attr:`~definition.__name__` and :attr:`__doc__` attributes
Georg Brandl9afde1c2007-11-01 20:32:30 +0000447 (properties, getsets, and members have both of these attributes), but this is
448 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000449
Georg Brandl116aa622007-08-15 14:28:22 +0000450
451.. function:: isgetsetdescriptor(object)
452
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200453 Return ``True`` if the object is a getset descriptor.
Georg Brandl116aa622007-08-15 14:28:22 +0000454
Georg Brandl495f7b52009-10-27 15:28:25 +0000455 .. impl-detail::
456
457 getsets are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000458 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000459 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000460
Georg Brandl116aa622007-08-15 14:28:22 +0000461
462.. function:: ismemberdescriptor(object)
463
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200464 Return ``True`` if the object is a member descriptor.
Georg Brandl116aa622007-08-15 14:28:22 +0000465
Georg Brandl495f7b52009-10-27 15:28:25 +0000466 .. impl-detail::
467
468 Member descriptors are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000469 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000470 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000471
Georg Brandl116aa622007-08-15 14:28:22 +0000472
473.. _inspect-source:
474
475Retrieving source code
476----------------------
477
Georg Brandl116aa622007-08-15 14:28:22 +0000478.. function:: getdoc(object)
479
Georg Brandl0c77a822008-06-10 16:37:50 +0000480 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300481 If the documentation string for an object is not provided and the object is
Serhiy Storchaka08b47c32020-05-18 20:25:07 +0300482 a class, a method, a property or a descriptor, retrieve the documentation
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300483 string from the inheritance hierarchy.
Georg Brandl116aa622007-08-15 14:28:22 +0000484
Berker Peksag4333d8b2015-07-30 18:06:09 +0300485 .. versionchanged:: 3.5
486 Documentation strings are now inherited if not overridden.
487
Georg Brandl116aa622007-08-15 14:28:22 +0000488
489.. function:: getcomments(object)
490
491 Return in a single string any lines of comments immediately preceding the
492 object's source code (for a class, function, or method), or at the top of the
Marco Buttu3f2155f2017-03-17 09:50:23 +0100493 Python source file (if the object is a module). If the object's source code
494 is unavailable, return ``None``. This could happen if the object has been
495 defined in C or the interactive shell.
Georg Brandl116aa622007-08-15 14:28:22 +0000496
497
498.. function:: getfile(object)
499
500 Return the name of the (text or binary) file in which an object was defined.
501 This will fail with a :exc:`TypeError` if the object is a built-in module,
502 class, or function.
503
504
505.. function:: getmodule(object)
506
507 Try to guess which module an object was defined in.
508
509
510.. function:: getsourcefile(object)
511
512 Return the name of the Python source file in which an object was defined. This
513 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
514 function.
515
516
517.. function:: getsourcelines(object)
518
519 Return a list of source lines and starting line number for an object. The
520 argument may be a module, class, method, function, traceback, frame, or code
521 object. The source code is returned as a list of the lines corresponding to the
522 object and the line number indicates where in the original source file the first
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200523 line of code was found. An :exc:`OSError` is raised if the source code cannot
Georg Brandl116aa622007-08-15 14:28:22 +0000524 be retrieved.
525
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200526 .. versionchanged:: 3.3
527 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
528 former.
529
Georg Brandl116aa622007-08-15 14:28:22 +0000530
531.. function:: getsource(object)
532
533 Return the text of the source code for an object. The argument may be a module,
534 class, method, function, traceback, frame, or code object. The source code is
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200535 returned as a single string. An :exc:`OSError` is raised if the source code
Georg Brandl116aa622007-08-15 14:28:22 +0000536 cannot be retrieved.
537
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200538 .. versionchanged:: 3.3
539 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
540 former.
541
Georg Brandl116aa622007-08-15 14:28:22 +0000542
Georg Brandl0c77a822008-06-10 16:37:50 +0000543.. function:: cleandoc(doc)
544
545 Clean up indentation from docstrings that are indented to line up with blocks
Senthil Kumaranebd84e32016-05-29 20:36:58 -0700546 of code.
547
548 All leading whitespace is removed from the first line. Any leading whitespace
549 that can be uniformly removed from the second line onwards is removed. Empty
550 lines at the beginning and end are subsequently removed. Also, all tabs are
551 expanded to spaces.
Georg Brandl0c77a822008-06-10 16:37:50 +0000552
Georg Brandl0c77a822008-06-10 16:37:50 +0000553
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300554.. _inspect-signature-object:
555
Georg Brandle4717722012-08-14 09:45:28 +0200556Introspecting callables with the Signature object
557-------------------------------------------------
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300558
559.. versionadded:: 3.3
560
Georg Brandle4717722012-08-14 09:45:28 +0200561The Signature object represents the call signature of a callable object and its
562return annotation. To retrieve a Signature object, use the :func:`signature`
563function.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300564
Batuhan Taskayaeee1c772020-12-24 01:45:13 +0300565.. function:: signature(callable, *, follow_wrapped=True, globalns=None, localns=None)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300566
Georg Brandle4717722012-08-14 09:45:28 +0200567 Return a :class:`Signature` object for the given ``callable``::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300568
569 >>> from inspect import signature
570 >>> def foo(a, *, b:int, **kwargs):
571 ... pass
572
573 >>> sig = signature(foo)
574
575 >>> str(sig)
576 '(a, *, b:int, **kwargs)'
577
578 >>> str(sig.parameters['b'])
579 'b:int'
580
581 >>> sig.parameters['b'].annotation
582 <class 'int'>
583
Andrés Delfino271818f2018-09-14 14:13:09 -0300584 Accepts a wide range of Python callables, from plain functions and classes to
Georg Brandle4717722012-08-14 09:45:28 +0200585 :func:`functools.partial` objects.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300586
Larry Hastings5c661892014-01-24 06:17:25 -0800587 Raises :exc:`ValueError` if no signature can be provided, and
588 :exc:`TypeError` if that type of object is not supported.
589
Batuhan Taskayaeee1c772020-12-24 01:45:13 +0300590 ``globalns`` and ``localns`` are passed into
591 :func:`typing.get_type_hints` when resolving the annotations.
592
Lysandros Nikolaou1aeeaeb2019-03-10 12:30:11 +0100593 A slash(/) in the signature of a function denotes that the parameters prior
594 to it are positional-only. For more info, see
595 :ref:`the FAQ entry on positional-only parameters <faq-positional-only-arguments>`.
596
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400597 .. versionadded:: 3.5
598 ``follow_wrapped`` parameter. Pass ``False`` to get a signature of
599 ``callable`` specifically (``callable.__wrapped__`` will not be used to
600 unwrap decorated callables.)
601
Batuhan Taskayaeee1c772020-12-24 01:45:13 +0300602 .. versionadded:: 3.10
603 ``globalns`` and ``localns`` parameters.
604
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300605 .. note::
606
Georg Brandle4717722012-08-14 09:45:28 +0200607 Some callables may not be introspectable in certain implementations of
Yury Selivanovd71e52f2014-01-30 00:22:57 -0500608 Python. For example, in CPython, some built-in functions defined in
609 C provide no metadata about their arguments.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300610
Batuhan Taskayaeee1c772020-12-24 01:45:13 +0300611 .. note::
612
613 Will first try to resolve the annotations, but when it fails and
614 encounters with an error while that operation, the annotations will be
615 returned unchanged (as strings).
616
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300617
Andre Delfinodcc997c2020-12-16 22:37:28 -0300618.. class:: Signature(parameters=None, *, return_annotation=Signature.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300619
Georg Brandle4717722012-08-14 09:45:28 +0200620 A Signature object represents the call signature of a function and its return
621 annotation. For each parameter accepted by the function it stores a
622 :class:`Parameter` object in its :attr:`parameters` collection.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300623
Yury Selivanov78356892014-01-30 00:10:54 -0500624 The optional *parameters* argument is a sequence of :class:`Parameter`
625 objects, which is validated to check that there are no parameters with
626 duplicate names, and that the parameters are in the right order, i.e.
627 positional-only first, then positional-or-keyword, and that parameters with
628 defaults follow parameters without defaults.
629
630 The optional *return_annotation* argument, can be an arbitrary Python object,
631 is the "return" annotation of the callable.
632
Georg Brandle4717722012-08-14 09:45:28 +0200633 Signature objects are *immutable*. Use :meth:`Signature.replace` to make a
634 modified copy.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300635
Yury Selivanov67d727e2014-03-29 13:24:14 -0400636 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400637 Signature objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400638
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300639 .. attribute:: Signature.empty
640
641 A special class-level marker to specify absence of a return annotation.
642
643 .. attribute:: Signature.parameters
644
Inada Naoki21105512020-03-02 18:54:49 +0900645 An ordered mapping of parameters' names to the corresponding
646 :class:`Parameter` objects. Parameters appear in strict definition
647 order, including keyword-only parameters.
larryhastingsf36ba122018-01-28 11:13:09 -0800648
649 .. versionchanged:: 3.7
650 Python only explicitly guaranteed that it preserved the declaration
651 order of keyword-only parameters as of version 3.7, although in practice
652 this order had always been preserved in Python 3.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300653
654 .. attribute:: Signature.return_annotation
655
Georg Brandle4717722012-08-14 09:45:28 +0200656 The "return" annotation for the callable. If the callable has no "return"
657 annotation, this attribute is set to :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300658
659 .. method:: Signature.bind(*args, **kwargs)
660
Georg Brandle4717722012-08-14 09:45:28 +0200661 Create a mapping from positional and keyword arguments to parameters.
662 Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
663 signature, or raises a :exc:`TypeError`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300664
665 .. method:: Signature.bind_partial(*args, **kwargs)
666
Georg Brandle4717722012-08-14 09:45:28 +0200667 Works the same way as :meth:`Signature.bind`, but allows the omission of
668 some required arguments (mimics :func:`functools.partial` behavior.)
669 Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
670 passed arguments do not match the signature.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300671
Ezio Melotti8429b672012-09-14 06:35:09 +0300672 .. method:: Signature.replace(*[, parameters][, return_annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300673
Georg Brandle4717722012-08-14 09:45:28 +0200674 Create a new Signature instance based on the instance replace was invoked
675 on. It is possible to pass different ``parameters`` and/or
676 ``return_annotation`` to override the corresponding properties of the base
677 signature. To remove return_annotation from the copied Signature, pass in
678 :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300679
680 ::
681
682 >>> def test(a, b):
683 ... pass
684 >>> sig = signature(test)
685 >>> new_sig = sig.replace(return_annotation="new return anno")
686 >>> str(new_sig)
687 "(a, b) -> 'new return anno'"
688
Batuhan Taskayaeee1c772020-12-24 01:45:13 +0300689 .. classmethod:: Signature.from_callable(obj, *, follow_wrapped=True, globalns=None, localns=None)
Yury Selivanovda396452014-03-27 12:09:24 -0400690
691 Return a :class:`Signature` (or its subclass) object for a given callable
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400692 ``obj``. Pass ``follow_wrapped=False`` to get a signature of ``obj``
Batuhan Taskayaeee1c772020-12-24 01:45:13 +0300693 without unwrapping its ``__wrapped__`` chain. ``globalns`` and
694 ``localns`` will be used as the namespaces when resolving annotations.
Yury Selivanovda396452014-03-27 12:09:24 -0400695
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400696 This method simplifies subclassing of :class:`Signature`::
Yury Selivanovda396452014-03-27 12:09:24 -0400697
698 class MySignature(Signature):
699 pass
700 sig = MySignature.from_callable(min)
701 assert isinstance(sig, MySignature)
702
Yury Selivanov232b9342014-03-29 13:18:30 -0400703 .. versionadded:: 3.5
704
Batuhan Taskayaeee1c772020-12-24 01:45:13 +0300705 .. versionadded:: 3.10
706 ``globalns`` and ``localns`` parameters.
707
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300708
Andre Delfinodcc997c2020-12-16 22:37:28 -0300709.. class:: Parameter(name, kind, *, default=Parameter.empty, annotation=Parameter.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300710
Georg Brandle4717722012-08-14 09:45:28 +0200711 Parameter objects are *immutable*. Instead of modifying a Parameter object,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300712 you can use :meth:`Parameter.replace` to create a modified copy.
713
Yury Selivanov67d727e2014-03-29 13:24:14 -0400714 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400715 Parameter objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400716
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300717 .. attribute:: Parameter.empty
718
Georg Brandle4717722012-08-14 09:45:28 +0200719 A special class-level marker to specify absence of default values and
720 annotations.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300721
722 .. attribute:: Parameter.name
723
Yury Selivanov2393dca2014-01-27 15:07:58 -0500724 The name of the parameter as a string. The name must be a valid
725 Python identifier.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300726
Nick Coghlanb4b966e2016-06-04 14:40:03 -0700727 .. impl-detail::
728
729 CPython generates implicit parameter names of the form ``.0`` on the
730 code objects used to implement comprehensions and generator
731 expressions.
732
733 .. versionchanged:: 3.6
734 These parameter names are exposed by this module as names like
735 ``implicit0``.
736
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300737 .. attribute:: Parameter.default
738
Georg Brandle4717722012-08-14 09:45:28 +0200739 The default value for the parameter. If the parameter has no default
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300740 value, this attribute is set to :attr:`Parameter.empty`.
741
742 .. attribute:: Parameter.annotation
743
Georg Brandle4717722012-08-14 09:45:28 +0200744 The annotation for the parameter. If the parameter has no annotation,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300745 this attribute is set to :attr:`Parameter.empty`.
746
747 .. attribute:: Parameter.kind
748
Georg Brandle4717722012-08-14 09:45:28 +0200749 Describes how argument values are bound to the parameter. Possible values
750 (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300751
Georg Brandl44ea77b2013-03-28 13:28:44 +0100752 .. tabularcolumns:: |l|L|
753
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300754 +------------------------+----------------------------------------------+
755 | Name | Meaning |
756 +========================+==============================================+
757 | *POSITIONAL_ONLY* | Value must be supplied as a positional |
Pablo Galindob76302d2019-05-29 00:45:32 +0100758 | | argument. Positional only parameters are |
759 | | those which appear before a ``/`` entry (if |
760 | | present) in a Python function definition. |
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300761 +------------------------+----------------------------------------------+
762 | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
763 | | positional argument (this is the standard |
764 | | binding behaviour for functions implemented |
765 | | in Python.) |
766 +------------------------+----------------------------------------------+
767 | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
768 | | bound to any other parameter. This |
769 | | corresponds to a ``*args`` parameter in a |
770 | | Python function definition. |
771 +------------------------+----------------------------------------------+
772 | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
773 | | Keyword only parameters are those which |
774 | | appear after a ``*`` or ``*args`` entry in a |
775 | | Python function definition. |
776 +------------------------+----------------------------------------------+
777 | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
778 | | to any other parameter. This corresponds to a|
779 | | ``**kwargs`` parameter in a Python function |
780 | | definition. |
781 +------------------------+----------------------------------------------+
782
Andrew Svetloveed18082012-08-13 18:23:54 +0300783 Example: print all keyword-only arguments without default values::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300784
785 >>> def foo(a, b, *, c, d=10):
786 ... pass
787
788 >>> sig = signature(foo)
789 >>> for param in sig.parameters.values():
790 ... if (param.kind == param.KEYWORD_ONLY and
791 ... param.default is param.empty):
792 ... print('Parameter:', param)
793 Parameter: c
794
Dong-hee Na4aa30062018-06-08 12:46:31 +0900795 .. attribute:: Parameter.kind.description
796
797 Describes a enum value of Parameter.kind.
798
Dong-hee Na4f548672018-06-09 01:07:52 +0900799 .. versionadded:: 3.8
800
Dong-hee Na4aa30062018-06-08 12:46:31 +0900801 Example: print all descriptions of arguments::
802
803 >>> def foo(a, b, *, c, d=10):
804 ... pass
805
806 >>> sig = signature(foo)
807 >>> for param in sig.parameters.values():
808 ... print(param.kind.description)
809 positional or keyword
810 positional or keyword
811 keyword-only
812 keyword-only
813
Ezio Melotti8429b672012-09-14 06:35:09 +0300814 .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300815
Georg Brandle4717722012-08-14 09:45:28 +0200816 Create a new Parameter instance based on the instance replaced was invoked
817 on. To override a :class:`Parameter` attribute, pass the corresponding
818 argument. To remove a default value or/and an annotation from a
819 Parameter, pass :attr:`Parameter.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300820
821 ::
822
823 >>> from inspect import Parameter
824 >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
825 >>> str(param)
826 'foo=42'
827
828 >>> str(param.replace()) # Will create a shallow copy of 'param'
829 'foo=42'
830
831 >>> str(param.replace(default=Parameter.empty, annotation='spam'))
832 "foo:'spam'"
833
Yury Selivanov2393dca2014-01-27 15:07:58 -0500834 .. versionchanged:: 3.4
835 In Python 3.3 Parameter objects were allowed to have ``name`` set
836 to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``.
837 This is no longer permitted.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300838
839.. class:: BoundArguments
840
841 Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
842 Holds the mapping of arguments to the function's parameters.
843
844 .. attribute:: BoundArguments.arguments
845
Inada Naoki21105512020-03-02 18:54:49 +0900846 A mutable mapping of parameters' names to arguments' values.
Rémi Lapeyre2cca8ef2020-01-28 13:47:03 +0100847 Contains only explicitly bound arguments. Changes in :attr:`arguments`
848 will reflect in :attr:`args` and :attr:`kwargs`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300849
Georg Brandle4717722012-08-14 09:45:28 +0200850 Should be used in conjunction with :attr:`Signature.parameters` for any
851 argument processing purposes.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300852
853 .. note::
854
855 Arguments for which :meth:`Signature.bind` or
856 :meth:`Signature.bind_partial` relied on a default value are skipped.
Yury Selivanovb907a512015-05-16 13:45:09 -0400857 However, if needed, use :meth:`BoundArguments.apply_defaults` to add
858 them.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300859
Rémi Lapeyre2cca8ef2020-01-28 13:47:03 +0100860 .. versionchanged:: 3.9
861 :attr:`arguments` is now of type :class:`dict`. Formerly, it was of
862 type :class:`collections.OrderedDict`.
863
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300864 .. attribute:: BoundArguments.args
865
Georg Brandle4717722012-08-14 09:45:28 +0200866 A tuple of positional arguments values. Dynamically computed from the
867 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300868
869 .. attribute:: BoundArguments.kwargs
870
Georg Brandle4717722012-08-14 09:45:28 +0200871 A dict of keyword arguments values. Dynamically computed from the
872 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300873
Yury Selivanov82796192015-05-14 14:14:02 -0400874 .. attribute:: BoundArguments.signature
875
876 A reference to the parent :class:`Signature` object.
877
Yury Selivanovb907a512015-05-16 13:45:09 -0400878 .. method:: BoundArguments.apply_defaults()
879
880 Set default values for missing arguments.
881
882 For variable-positional arguments (``*args``) the default is an
883 empty tuple.
884
885 For variable-keyword arguments (``**kwargs``) the default is an
886 empty dict.
887
888 ::
889
890 >>> def foo(a, b='ham', *args): pass
891 >>> ba = inspect.signature(foo).bind('spam')
892 >>> ba.apply_defaults()
893 >>> ba.arguments
Rémi Lapeyre2cca8ef2020-01-28 13:47:03 +0100894 {'a': 'spam', 'b': 'ham', 'args': ()}
Yury Selivanovb907a512015-05-16 13:45:09 -0400895
Berker Peksag5b3df5b2015-05-16 23:29:31 +0300896 .. versionadded:: 3.5
897
Georg Brandle4717722012-08-14 09:45:28 +0200898 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
899 functions::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300900
901 def test(a, *, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300902 ...
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300903
904 sig = signature(test)
905 ba = sig.bind(10, b=20)
906 test(*ba.args, **ba.kwargs)
907
908
Georg Brandle4717722012-08-14 09:45:28 +0200909.. seealso::
910
911 :pep:`362` - Function Signature Object.
912 The detailed specification, implementation details and examples.
913
914
Georg Brandl116aa622007-08-15 14:28:22 +0000915.. _inspect-classes-functions:
916
917Classes and functions
918---------------------
919
Georg Brandl3dd33882009-06-01 17:35:27 +0000920.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000921
922 Arrange the given list of classes into a hierarchy of nested lists. Where a
923 nested list appears, it contains classes derived from the class whose entry
924 immediately precedes the list. Each entry is a 2-tuple containing a class and a
925 tuple of its base classes. If the *unique* argument is true, exactly one entry
926 appears in the returned structure for each class in the given list. Otherwise,
927 classes using multiple inheritance and their descendants will appear multiple
928 times.
929
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500930
931.. function:: getargspec(func)
932
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000933 Get the names and default values of a Python function's parameters. A
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500934 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000935 returned. *args* is a list of the parameter names. *varargs* and *keywords*
936 are the names of the ``*`` and ``**`` parameters or ``None``. *defaults* is a
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500937 tuple of default argument values or ``None`` if there are no default
938 arguments; if this tuple has *n* elements, they correspond to the last
939 *n* elements listed in *args*.
940
941 .. deprecated:: 3.0
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000942 Use :func:`getfullargspec` for an updated API that is usually a drop-in
943 replacement, but also correctly handles function annotations and
944 keyword-only parameters.
945
946 Alternatively, use :func:`signature` and
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500947 :ref:`Signature Object <inspect-signature-object>`, which provide a
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000948 more structured introspection API for callables.
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500949
950
Georg Brandl138bcb52007-09-12 19:04:21 +0000951.. function:: getfullargspec(func)
952
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000953 Get the names and default values of a Python function's parameters. A
Georg Brandl82402752010-01-09 09:48:46 +0000954 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000955
Georg Brandl3dd33882009-06-01 17:35:27 +0000956 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
957 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000958
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000959 *args* is a list of the positional parameter names.
960 *varargs* is the name of the ``*`` parameter or ``None`` if arbitrary
961 positional arguments are not accepted.
962 *varkw* is the name of the ``**`` parameter or ``None`` if arbitrary
963 keyword arguments are not accepted.
964 *defaults* is an *n*-tuple of default argument values corresponding to the
965 last *n* positional parameters, or ``None`` if there are no such defaults
966 defined.
larryhastingsf36ba122018-01-28 11:13:09 -0800967 *kwonlyargs* is a list of keyword-only parameter names in declaration order.
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000968 *kwonlydefaults* is a dictionary mapping parameter names from *kwonlyargs*
969 to the default values used if no argument is supplied.
970 *annotations* is a dictionary mapping parameter names to annotations.
971 The special key ``"return"`` is used to report the function return value
972 annotation (if any).
973
974 Note that :func:`signature` and
975 :ref:`Signature Object <inspect-signature-object>` provide the recommended
976 API for callable introspection, and support additional behaviours (like
977 positional-only arguments) that are sometimes encountered in extension module
978 APIs. This function is retained primarily for use in code that needs to
979 maintain compatibility with the Python 2 ``inspect`` module API.
Georg Brandl138bcb52007-09-12 19:04:21 +0000980
Nick Coghlan16355782014-03-08 16:36:37 +1000981 .. versionchanged:: 3.4
982 This function is now based on :func:`signature`, but still ignores
983 ``__wrapped__`` attributes and includes the already bound first
984 parameter in the signature output for bound methods.
985
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000986 .. versionchanged:: 3.6
987 This method was previously documented as deprecated in favour of
988 :func:`signature` in Python 3.5, but that decision has been reversed
989 in order to restore a clearly supported standard interface for
990 single-source Python 2/3 code migrating away from the legacy
991 :func:`getargspec` API.
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400992
larryhastingsf36ba122018-01-28 11:13:09 -0800993 .. versionchanged:: 3.7
994 Python only explicitly guaranteed that it preserved the declaration
995 order of keyword-only parameters as of version 3.7, although in practice
996 this order had always been preserved in Python 3.
997
Georg Brandl116aa622007-08-15 14:28:22 +0000998
999.. function:: getargvalues(frame)
1000
Georg Brandl3dd33882009-06-01 17:35:27 +00001001 Get information about arguments passed into a particular frame. A
1002 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +00001003 returned. *args* is a list of the argument names. *varargs* and *keywords*
1004 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001005 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +00001006
Matthias Bussonnier0899b982017-02-21 21:45:51 -08001007 .. note::
1008 This function was inadvertently marked as deprecated in Python 3.5.
Yury Selivanov945fff42015-05-22 16:28:05 -04001009
Georg Brandl116aa622007-08-15 14:28:22 +00001010
Andrew Svetlov735d3172012-10-27 00:28:20 +03001011.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Georg Brandl116aa622007-08-15 14:28:22 +00001012
Michael Foord3af125a2012-04-21 18:22:28 +01001013 Format a pretty argument spec from the values returned by
Berker Peksagfa3922c2015-07-31 04:11:29 +03001014 :func:`getfullargspec`.
Michael Foord3af125a2012-04-21 18:22:28 +01001015
1016 The first seven arguments are (``args``, ``varargs``, ``varkw``,
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001017 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
Andrew Svetlov735d3172012-10-27 00:28:20 +03001018
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001019 The other six arguments are functions that are called to turn argument names,
1020 ``*`` argument name, ``**`` argument name, default values, return annotation
1021 and individual annotations into strings, respectively.
1022
1023 For example:
1024
1025 >>> from inspect import formatargspec, getfullargspec
1026 >>> def f(a: int, b: float):
1027 ... pass
1028 ...
1029 >>> formatargspec(*getfullargspec(f))
1030 '(a: int, b: float)'
Georg Brandl116aa622007-08-15 14:28:22 +00001031
Yury Selivanov945fff42015-05-22 16:28:05 -04001032 .. deprecated:: 3.5
1033 Use :func:`signature` and
1034 :ref:`Signature Object <inspect-signature-object>`, which provide a
1035 better introspecting API for callables.
1036
Georg Brandl116aa622007-08-15 14:28:22 +00001037
Georg Brandlc1c4bf82010-10-15 16:07:41 +00001038.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +00001039
1040 Format a pretty argument spec from the four values returned by
1041 :func:`getargvalues`. The format\* arguments are the corresponding optional
1042 formatting functions that are called to turn names and values into strings.
1043
Matthias Bussonnier0899b982017-02-21 21:45:51 -08001044 .. note::
1045 This function was inadvertently marked as deprecated in Python 3.5.
Yury Selivanov945fff42015-05-22 16:28:05 -04001046
Georg Brandl116aa622007-08-15 14:28:22 +00001047
1048.. function:: getmro(cls)
1049
1050 Return a tuple of class cls's base classes, including cls, in method resolution
1051 order. No class appears more than once in this tuple. Note that the method
1052 resolution order depends on cls's type. Unless a very peculiar user-defined
1053 metatype is in use, cls will be the first element of the tuple.
1054
1055
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001056.. function:: getcallargs(func, /, *args, **kwds)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001057
1058 Bind the *args* and *kwds* to the argument names of the Python function or
1059 method *func*, as if it was called with them. For bound methods, bind also the
1060 first argument (typically named ``self``) to the associated instance. A dict
1061 is returned, mapping the argument names (including the names of the ``*`` and
1062 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
1063 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
1064 an exception because of incompatible signature, an exception of the same type
1065 and the same or similar message is raised. For example::
1066
1067 >>> from inspect import getcallargs
1068 >>> def f(a, b=1, *pos, **named):
1069 ... pass
Andrew Svetlove939f382012-08-09 13:25:32 +03001070 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
1071 True
1072 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
1073 True
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001074 >>> getcallargs(f)
1075 Traceback (most recent call last):
1076 ...
Andrew Svetlove939f382012-08-09 13:25:32 +03001077 TypeError: f() missing 1 required positional argument: 'a'
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001078
1079 .. versionadded:: 3.2
1080
Yury Selivanov3cfec2e2015-05-22 11:38:38 -04001081 .. deprecated:: 3.5
1082 Use :meth:`Signature.bind` and :meth:`Signature.bind_partial` instead.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +03001083
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001084
Nick Coghlan2f92e542012-06-23 19:39:55 +10001085.. function:: getclosurevars(func)
1086
1087 Get the mapping of external name references in a Python function or
1088 method *func* to their current values. A
1089 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
1090 is returned. *nonlocals* maps referenced names to lexical closure
1091 variables, *globals* to the function's module globals and *builtins* to
1092 the builtins visible from the function body. *unbound* is the set of names
1093 referenced in the function that could not be resolved at all given the
1094 current module globals and builtins.
1095
1096 :exc:`TypeError` is raised if *func* is not a Python function or method.
1097
1098 .. versionadded:: 3.3
1099
1100
Nick Coghlane8c45d62013-07-28 20:00:01 +10001101.. function:: unwrap(func, *, stop=None)
1102
1103 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
1104 attributes returning the last object in the chain.
1105
1106 *stop* is an optional callback accepting an object in the wrapper chain
1107 as its sole argument that allows the unwrapping to be terminated early if
1108 the callback returns a true value. If the callback never returns a true
1109 value, the last object in the chain is returned as usual. For example,
1110 :func:`signature` uses this to stop unwrapping if any object in the
1111 chain has a ``__signature__`` attribute defined.
1112
1113 :exc:`ValueError` is raised if a cycle is encountered.
1114
1115 .. versionadded:: 3.4
1116
1117
Georg Brandl116aa622007-08-15 14:28:22 +00001118.. _inspect-stack:
1119
1120The interpreter stack
1121---------------------
1122
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001123When the following functions return "frame records," each record is a
1124:term:`named tuple`
1125``FrameInfo(frame, filename, lineno, function, code_context, index)``.
1126The tuple contains the frame object, the filename, the line number of the
1127current line,
Georg Brandl116aa622007-08-15 14:28:22 +00001128the function name, a list of lines of context from the source code, and the
1129index of the current line within that list.
1130
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001131.. versionchanged:: 3.5
1132 Return a named tuple instead of a tuple.
1133
Georg Brandle720c0a2009-04-27 16:20:50 +00001134.. note::
Georg Brandl116aa622007-08-15 14:28:22 +00001135
1136 Keeping references to frame objects, as found in the first element of the frame
1137 records these functions return, can cause your program to create reference
1138 cycles. Once a reference cycle has been created, the lifespan of all objects
1139 which can be accessed from the objects which form the cycle can become much
1140 longer even if Python's optional cycle detector is enabled. If such cycles must
1141 be created, it is important to ensure they are explicitly broken to avoid the
1142 delayed destruction of objects and increased memory consumption which occurs.
1143
1144 Though the cycle detector will catch these, destruction of the frames (and local
1145 variables) can be made deterministic by removing the cycle in a
1146 :keyword:`finally` clause. This is also important if the cycle detector was
1147 disabled when Python was compiled or using :func:`gc.disable`. For example::
1148
1149 def handle_stackframe_without_leak():
1150 frame = inspect.currentframe()
1151 try:
1152 # do something with the frame
1153 finally:
1154 del frame
1155
Antoine Pitrou58720d62013-08-05 23:26:40 +02001156 If you want to keep the frame around (for example to print a traceback
1157 later), you can also break reference cycles by using the
1158 :meth:`frame.clear` method.
1159
Georg Brandl116aa622007-08-15 14:28:22 +00001160The optional *context* argument supported by most of these functions specifies
1161the number of lines of context to return, which are centered around the current
1162line.
1163
1164
Georg Brandl3dd33882009-06-01 17:35:27 +00001165.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001166
Georg Brandl48310cd2009-01-03 21:18:54 +00001167 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +00001168 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +00001169
1170
Georg Brandl3dd33882009-06-01 17:35:27 +00001171.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001172
1173 Get a list of frame records for a frame and all outer frames. These frames
1174 represent the calls that lead to the creation of *frame*. The first entry in the
1175 returned list represents *frame*; the last entry represents the outermost call
1176 on *frame*'s stack.
1177
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001178 .. versionchanged:: 3.5
1179 A list of :term:`named tuples <named tuple>`
1180 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1181 is returned.
1182
Georg Brandl116aa622007-08-15 14:28:22 +00001183
Georg Brandl3dd33882009-06-01 17:35:27 +00001184.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001185
1186 Get a list of frame records for a traceback's frame and all inner frames. These
1187 frames represent calls made as a consequence of *frame*. The first entry in the
1188 list represents *traceback*; the last entry represents where the exception was
1189 raised.
1190
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001191 .. versionchanged:: 3.5
1192 A list of :term:`named tuples <named tuple>`
1193 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1194 is returned.
1195
Georg Brandl116aa622007-08-15 14:28:22 +00001196
1197.. function:: currentframe()
1198
1199 Return the frame object for the caller's stack frame.
1200
Georg Brandl495f7b52009-10-27 15:28:25 +00001201 .. impl-detail::
1202
1203 This function relies on Python stack frame support in the interpreter,
1204 which isn't guaranteed to exist in all implementations of Python. If
1205 running in an implementation without Python stack frame support this
1206 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001207
Georg Brandl116aa622007-08-15 14:28:22 +00001208
Georg Brandl3dd33882009-06-01 17:35:27 +00001209.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001210
1211 Return a list of frame records for the caller's stack. The first entry in the
1212 returned list represents the caller; the last entry represents the outermost
1213 call on the stack.
1214
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001215 .. versionchanged:: 3.5
1216 A list of :term:`named tuples <named tuple>`
1217 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1218 is returned.
1219
Georg Brandl116aa622007-08-15 14:28:22 +00001220
Georg Brandl3dd33882009-06-01 17:35:27 +00001221.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001222
1223 Return a list of frame records for the stack between the current frame and the
1224 frame in which an exception currently being handled was raised in. The first
1225 entry in the list represents the caller; the last entry represents where the
1226 exception was raised.
1227
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001228 .. versionchanged:: 3.5
1229 A list of :term:`named tuples <named tuple>`
1230 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1231 is returned.
1232
Michael Foord95fc51d2010-11-20 15:07:30 +00001233
1234Fetching attributes statically
1235------------------------------
1236
1237Both :func:`getattr` and :func:`hasattr` can trigger code execution when
1238fetching or checking for the existence of attributes. Descriptors, like
1239properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
1240may be called.
1241
1242For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +02001243can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +00001244but avoids executing code when it fetches attributes.
1245
1246.. function:: getattr_static(obj, attr, default=None)
1247
1248 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +02001249 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +00001250
1251 Note: this function may not be able to retrieve all attributes
1252 that getattr can fetch (like dynamically created attributes)
1253 and may find attributes that getattr can't (like descriptors
1254 that raise AttributeError). It can also return descriptors objects
1255 instead of instance members.
1256
Serhiy Storchakabfdcd432013-10-13 23:09:14 +03001257 If the instance :attr:`~object.__dict__` is shadowed by another member (for
1258 example a property) then this function will be unable to find instance
1259 members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001260
Michael Foorddcebe0f2011-03-15 19:20:44 -04001261 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +00001262
Éric Araujo941afed2011-09-01 02:47:34 +02001263:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +00001264getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +00001265is returned instead of the underlying attribute.
1266
1267You can handle these with code like the following. Note that
1268for arbitrary getset descriptors invoking these may trigger
1269code execution::
1270
1271 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +00001272 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +00001273 __slots__ = ['foo']
1274
1275 slot_descriptor = type(_foo.foo)
1276 getset_descriptor = type(type(open(__file__)).name)
1277 wrapper_descriptor = type(str.__dict__['__add__'])
1278 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
1279
1280 result = getattr_static(some_object, 'foo')
1281 if type(result) in descriptor_types:
1282 try:
1283 result = result.__get__()
1284 except AttributeError:
1285 # descriptors can raise AttributeError to
1286 # indicate there is no underlying value
1287 # in which case the descriptor itself will
1288 # have to do
1289 pass
Nick Coghlane0f04652010-11-21 03:44:04 +00001290
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001291
Yury Selivanov5376ba92015-06-22 12:19:30 -04001292Current State of Generators and Coroutines
1293------------------------------------------
Nick Coghlane0f04652010-11-21 03:44:04 +00001294
1295When implementing coroutine schedulers and for other advanced uses of
1296generators, it is useful to determine whether a generator is currently
1297executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001298terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +00001299generator to be determined easily.
1300
1301.. function:: getgeneratorstate(generator)
1302
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001303 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +00001304
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001305 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +00001306 * GEN_CREATED: Waiting to start execution.
1307 * GEN_RUNNING: Currently being executed by the interpreter.
1308 * GEN_SUSPENDED: Currently suspended at a yield expression.
1309 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +00001310
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001311 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001312
Yury Selivanov5376ba92015-06-22 12:19:30 -04001313.. function:: getcoroutinestate(coroutine)
1314
1315 Get current state of a coroutine object. The function is intended to be
1316 used with coroutine objects created by :keyword:`async def` functions, but
1317 will accept any coroutine-like object that has ``cr_running`` and
1318 ``cr_frame`` attributes.
1319
1320 Possible states are:
1321 * CORO_CREATED: Waiting to start execution.
1322 * CORO_RUNNING: Currently being executed by the interpreter.
1323 * CORO_SUSPENDED: Currently suspended at an await expression.
1324 * CORO_CLOSED: Execution has completed.
1325
1326 .. versionadded:: 3.5
1327
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001328The current internal state of the generator can also be queried. This is
1329mostly useful for testing purposes, to ensure that internal state is being
1330updated as expected:
1331
1332.. function:: getgeneratorlocals(generator)
1333
1334 Get the mapping of live local variables in *generator* to their current
1335 values. A dictionary is returned that maps from variable names to values.
1336 This is the equivalent of calling :func:`locals` in the body of the
1337 generator, and all the same caveats apply.
1338
1339 If *generator* is a :term:`generator` with no currently associated frame,
1340 then an empty dictionary is returned. :exc:`TypeError` is raised if
1341 *generator* is not a Python generator object.
1342
1343 .. impl-detail::
1344
1345 This function relies on the generator exposing a Python stack frame
1346 for introspection, which isn't guaranteed to be the case in all
1347 implementations of Python. In such cases, this function will always
1348 return an empty dictionary.
1349
1350 .. versionadded:: 3.3
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001351
Yury Selivanov5376ba92015-06-22 12:19:30 -04001352.. function:: getcoroutinelocals(coroutine)
1353
1354 This function is analogous to :func:`~inspect.getgeneratorlocals`, but
1355 works for coroutine objects created by :keyword:`async def` functions.
1356
1357 .. versionadded:: 3.5
1358
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001359
Yury Selivanovea75a512016-10-20 13:06:30 -04001360.. _inspect-module-co-flags:
1361
1362Code Objects Bit Flags
1363----------------------
1364
1365Python code objects have a ``co_flags`` attribute, which is a bitmap of
1366the following flags:
1367
Xiang Zhanga6902e62017-04-13 10:38:28 +08001368.. data:: CO_OPTIMIZED
1369
1370 The code object is optimized, using fast locals.
1371
Yury Selivanovea75a512016-10-20 13:06:30 -04001372.. data:: CO_NEWLOCALS
1373
1374 If set, a new dict will be created for the frame's ``f_locals`` when
1375 the code object is executed.
1376
1377.. data:: CO_VARARGS
1378
1379 The code object has a variable positional parameter (``*args``-like).
1380
1381.. data:: CO_VARKEYWORDS
1382
1383 The code object has a variable keyword parameter (``**kwargs``-like).
1384
Xiang Zhanga6902e62017-04-13 10:38:28 +08001385.. data:: CO_NESTED
1386
1387 The flag is set when the code object is a nested function.
1388
Yury Selivanovea75a512016-10-20 13:06:30 -04001389.. data:: CO_GENERATOR
1390
1391 The flag is set when the code object is a generator function, i.e.
1392 a generator object is returned when the code object is executed.
1393
1394.. data:: CO_NOFREE
1395
1396 The flag is set if there are no free or cell variables.
1397
1398.. data:: CO_COROUTINE
1399
Yury Selivanovb738a1f2016-10-20 16:30:51 -04001400 The flag is set when the code object is a coroutine function.
1401 When the code object is executed it returns a coroutine object.
1402 See :pep:`492` for more details.
Yury Selivanovea75a512016-10-20 13:06:30 -04001403
1404 .. versionadded:: 3.5
1405
1406.. data:: CO_ITERABLE_COROUTINE
1407
Yury Selivanovb738a1f2016-10-20 16:30:51 -04001408 The flag is used to transform generators into generator-based
1409 coroutines. Generator objects with this flag can be used in
1410 ``await`` expression, and can ``yield from`` coroutine objects.
1411 See :pep:`492` for more details.
Yury Selivanovea75a512016-10-20 13:06:30 -04001412
1413 .. versionadded:: 3.5
1414
Yury Selivanove20fed92016-10-20 13:11:34 -04001415.. data:: CO_ASYNC_GENERATOR
1416
Yury Selivanovb738a1f2016-10-20 16:30:51 -04001417 The flag is set when the code object is an asynchronous generator
1418 function. When the code object is executed it returns an
1419 asynchronous generator object. See :pep:`525` for more details.
Yury Selivanove20fed92016-10-20 13:11:34 -04001420
1421 .. versionadded:: 3.6
1422
Yury Selivanovea75a512016-10-20 13:06:30 -04001423.. note::
1424 The flags are specific to CPython, and may not be defined in other
1425 Python implementations. Furthermore, the flags are an implementation
1426 detail, and can be removed or deprecated in future Python releases.
1427 It's recommended to use public APIs from the :mod:`inspect` module
1428 for any introspection needs.
1429
1430
Nick Coghlan367df122013-10-27 01:57:34 +10001431.. _inspect-module-cli:
1432
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001433Command Line Interface
1434----------------------
1435
1436The :mod:`inspect` module also provides a basic introspection capability
1437from the command line.
1438
1439.. program:: inspect
1440
1441By default, accepts the name of a module and prints the source of that
1442module. A class or function within the module can be printed instead by
1443appended a colon and the qualified name of the target object.
1444
1445.. cmdoption:: --details
1446
1447 Print information about the specified object rather than the source code