blob: 6be28a2b31cb66ac9ac53529a47b1e7954d318cd [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
Xiang Zhanga6902e62017-04-13 10:38:28 +080037+-----------+-------------------+---------------------------+
38| Type | Attribute | Description |
39+===========+===================+===========================+
40| module | __doc__ | documentation string |
41+-----------+-------------------+---------------------------+
42| | __file__ | filename (missing for |
43| | | built-in modules) |
44+-----------+-------------------+---------------------------+
45| class | __doc__ | documentation string |
46+-----------+-------------------+---------------------------+
47| | __name__ | name with which this |
48| | | class was defined |
49+-----------+-------------------+---------------------------+
50| | __qualname__ | qualified name |
51+-----------+-------------------+---------------------------+
52| | __module__ | name of module in which |
53| | | this class was defined |
54+-----------+-------------------+---------------------------+
55| method | __doc__ | documentation string |
56+-----------+-------------------+---------------------------+
57| | __name__ | name with which this |
58| | | method was defined |
59+-----------+-------------------+---------------------------+
60| | __qualname__ | qualified name |
61+-----------+-------------------+---------------------------+
62| | __func__ | function object |
63| | | containing implementation |
64| | | of method |
65+-----------+-------------------+---------------------------+
66| | __self__ | instance to which this |
67| | | method is bound, or |
68| | | ``None`` |
69+-----------+-------------------+---------------------------+
70| function | __doc__ | documentation string |
71+-----------+-------------------+---------------------------+
72| | __name__ | name with which this |
73| | | function was defined |
74+-----------+-------------------+---------------------------+
75| | __qualname__ | qualified name |
76+-----------+-------------------+---------------------------+
77| | __code__ | code object containing |
78| | | compiled function |
79| | | :term:`bytecode` |
80+-----------+-------------------+---------------------------+
81| | __defaults__ | tuple of any default |
82| | | values for positional or |
83| | | keyword parameters |
84+-----------+-------------------+---------------------------+
85| | __kwdefaults__ | mapping of any default |
86| | | values for keyword-only |
87| | | parameters |
88+-----------+-------------------+---------------------------+
89| | __globals__ | global namespace in which |
90| | | this function was defined |
91+-----------+-------------------+---------------------------+
92| | __annotations__ | mapping of parameters |
93| | | names to annotations; |
94| | | ``"return"`` key is |
95| | | reserved for return |
96| | | annotations. |
97+-----------+-------------------+---------------------------+
98| traceback | tb_frame | frame object at this |
99| | | level |
100+-----------+-------------------+---------------------------+
101| | tb_lasti | index of last attempted |
102| | | instruction in bytecode |
103+-----------+-------------------+---------------------------+
104| | tb_lineno | current line number in |
105| | | Python source code |
106+-----------+-------------------+---------------------------+
107| | tb_next | next inner traceback |
108| | | object (called by this |
109| | | level) |
110+-----------+-------------------+---------------------------+
111| frame | f_back | next outer frame object |
112| | | (this frame's caller) |
113+-----------+-------------------+---------------------------+
114| | f_builtins | builtins namespace seen |
115| | | by this frame |
116+-----------+-------------------+---------------------------+
117| | f_code | code object being |
118| | | executed in this frame |
119+-----------+-------------------+---------------------------+
120| | f_globals | global namespace seen by |
121| | | this frame |
122+-----------+-------------------+---------------------------+
123| | f_lasti | index of last attempted |
124| | | instruction in bytecode |
125+-----------+-------------------+---------------------------+
126| | f_lineno | current line number in |
127| | | Python source code |
128+-----------+-------------------+---------------------------+
129| | f_locals | local namespace seen by |
130| | | this frame |
131+-----------+-------------------+---------------------------+
132| | f_restricted | 0 or 1 if frame is in |
133| | | restricted execution mode |
134+-----------+-------------------+---------------------------+
135| | f_trace | tracing function for this |
136| | | frame, or ``None`` |
137+-----------+-------------------+---------------------------+
138| code | co_argcount | number of arguments (not |
139| | | including keyword only |
140| | | arguments, \* or \*\* |
141| | | args) |
142+-----------+-------------------+---------------------------+
143| | co_code | string of raw compiled |
144| | | bytecode |
145+-----------+-------------------+---------------------------+
146| | co_cellvars | tuple of names of cell |
147| | | variables (referenced by |
148| | | containing scopes) |
149+-----------+-------------------+---------------------------+
150| | co_consts | tuple of constants used |
151| | | in the bytecode |
152+-----------+-------------------+---------------------------+
153| | co_filename | name of file in which |
154| | | this code object was |
155| | | created |
156+-----------+-------------------+---------------------------+
157| | co_firstlineno | number of first line in |
158| | | Python source code |
159+-----------+-------------------+---------------------------+
160| | co_flags | bitmap of ``CO_*`` flags, |
161| | | read more :ref:`here |
162| | | <inspect-module-co-flags>`|
163+-----------+-------------------+---------------------------+
164| | co_lnotab | encoded mapping of line |
165| | | numbers to bytecode |
166| | | indices |
167+-----------+-------------------+---------------------------+
168| | co_freevars | tuple of names of free |
169| | | variables (referenced via |
170| | | a function's closure) |
171+-----------+-------------------+---------------------------+
172| | co_kwonlyargcount | number of keyword only |
173| | | arguments (not including |
174| | | \*\* arg) |
175+-----------+-------------------+---------------------------+
176| | co_name | name with which this code |
177| | | object was defined |
178+-----------+-------------------+---------------------------+
179| | co_names | tuple of names of local |
180| | | variables |
181+-----------+-------------------+---------------------------+
182| | co_nlocals | number of local variables |
183+-----------+-------------------+---------------------------+
184| | co_stacksize | virtual machine stack |
185| | | space required |
186+-----------+-------------------+---------------------------+
187| | co_varnames | tuple of names of |
188| | | arguments and local |
189| | | variables |
190+-----------+-------------------+---------------------------+
191| generator | __name__ | name |
192+-----------+-------------------+---------------------------+
193| | __qualname__ | qualified name |
194+-----------+-------------------+---------------------------+
195| | gi_frame | frame |
196+-----------+-------------------+---------------------------+
197| | gi_running | is the generator running? |
198+-----------+-------------------+---------------------------+
199| | gi_code | code |
200+-----------+-------------------+---------------------------+
201| | gi_yieldfrom | object being iterated by |
202| | | ``yield from``, or |
203| | | ``None`` |
204+-----------+-------------------+---------------------------+
205| coroutine | __name__ | name |
206+-----------+-------------------+---------------------------+
207| | __qualname__ | qualified name |
208+-----------+-------------------+---------------------------+
209| | cr_await | object being awaited on, |
210| | | or ``None`` |
211+-----------+-------------------+---------------------------+
212| | cr_frame | frame |
213+-----------+-------------------+---------------------------+
214| | cr_running | is the coroutine running? |
215+-----------+-------------------+---------------------------+
216| | cr_code | code |
217+-----------+-------------------+---------------------------+
218| builtin | __doc__ | documentation string |
219+-----------+-------------------+---------------------------+
220| | __name__ | original name of this |
221| | | function or method |
222+-----------+-------------------+---------------------------+
223| | __qualname__ | qualified name |
224+-----------+-------------------+---------------------------+
225| | __self__ | instance to which a |
226| | | method is bound, or |
227| | | ``None`` |
228+-----------+-------------------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000229
Victor Stinner40ee3012014-06-16 15:59:28 +0200230.. versionchanged:: 3.5
231
Yury Selivanov5fbad3c2015-08-17 13:04:41 -0400232 Add ``__qualname__`` and ``gi_yieldfrom`` attributes to generators.
233
234 The ``__name__`` attribute of generators is now set from the function
235 name, instead of the code name, and it can now be modified.
Victor Stinner40ee3012014-06-16 15:59:28 +0200236
Georg Brandl116aa622007-08-15 14:28:22 +0000237
238.. function:: getmembers(object[, predicate])
239
240 Return all the members of an object in a list of (name, value) pairs sorted by
241 name. If the optional *predicate* argument is supplied, only members for which
242 the predicate returns a true value are included.
243
Christian Heimes7f044312008-01-06 17:05:40 +0000244 .. note::
245
Ethan Furman63c141c2013-10-18 00:27:39 -0700246 :func:`getmembers` will only return class attributes defined in the
247 metaclass when the argument is a class and those attributes have been
248 listed in the metaclass' custom :meth:`__dir__`.
Christian Heimes7f044312008-01-06 17:05:40 +0000249
Georg Brandl116aa622007-08-15 14:28:22 +0000250
Georg Brandl116aa622007-08-15 14:28:22 +0000251.. function:: getmodulename(path)
252
253 Return the name of the module named by the file *path*, without including the
Nick Coghlan76e07702012-07-18 23:14:57 +1000254 names of enclosing packages. The file extension is checked against all of
255 the entries in :func:`importlib.machinery.all_suffixes`. If it matches,
256 the final path component is returned with the extension removed.
257 Otherwise, ``None`` is returned.
258
259 Note that this function *only* returns a meaningful name for actual
260 Python modules - paths that potentially refer to Python packages will
261 still return ``None``.
262
263 .. versionchanged:: 3.3
Yury Selivanov6dfbc5d2015-07-23 17:49:00 +0300264 The function is based directly on :mod:`importlib`.
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266
267.. function:: ismodule(object)
268
269 Return true if the object is a module.
270
271
272.. function:: isclass(object)
273
Georg Brandl39cadc32010-10-15 16:53:24 +0000274 Return true if the object is a class, whether built-in or created in Python
275 code.
Georg Brandl116aa622007-08-15 14:28:22 +0000276
277
278.. function:: ismethod(object)
279
Georg Brandl39cadc32010-10-15 16:53:24 +0000280 Return true if the object is a bound method written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282
283.. function:: isfunction(object)
284
Georg Brandl39cadc32010-10-15 16:53:24 +0000285 Return true if the object is a Python function, which includes functions
286 created by a :term:`lambda` expression.
Georg Brandl116aa622007-08-15 14:28:22 +0000287
288
Christian Heimes7131fd92008-02-19 14:21:46 +0000289.. function:: isgeneratorfunction(object)
290
291 Return true if the object is a Python generator function.
292
293
294.. function:: isgenerator(object)
295
296 Return true if the object is a generator.
297
298
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400299.. function:: iscoroutinefunction(object)
300
Yury Selivanov5376ba92015-06-22 12:19:30 -0400301 Return true if the object is a :term:`coroutine function`
302 (a function defined with an :keyword:`async def` syntax).
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400303
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400304 .. versionadded:: 3.5
305
306
307.. function:: iscoroutine(object)
308
Yury Selivanov5376ba92015-06-22 12:19:30 -0400309 Return true if the object is a :term:`coroutine` created by an
310 :keyword:`async def` function.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400311
312 .. versionadded:: 3.5
313
314
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400315.. function:: isawaitable(object)
316
317 Return true if the object can be used in :keyword:`await` expression.
318
319 Can also be used to distinguish generator-based coroutines from regular
320 generators::
321
322 def gen():
323 yield
324 @types.coroutine
325 def gen_coro():
326 yield
327
328 assert not isawaitable(gen())
329 assert isawaitable(gen_coro())
330
331 .. versionadded:: 3.5
332
333
Yury Selivanov03660042016-12-15 17:36:05 -0500334.. function:: isasyncgenfunction(object)
335
336 Return true if the object is an :term:`asynchronous generator` function,
337 for example::
338
339 >>> async def agen():
340 ... yield 1
341 ...
342 >>> inspect.isasyncgenfunction(agen)
343 True
344
345 .. versionadded:: 3.6
346
347
348.. function:: isasyncgen(object)
349
350 Return true if the object is an :term:`asynchronous generator iterator`
351 created by an :term:`asynchronous generator` function.
352
353 .. versionadded:: 3.6
354
Georg Brandl116aa622007-08-15 14:28:22 +0000355.. function:: istraceback(object)
356
357 Return true if the object is a traceback.
358
359
360.. function:: isframe(object)
361
362 Return true if the object is a frame.
363
364
365.. function:: iscode(object)
366
367 Return true if the object is a code.
368
369
370.. function:: isbuiltin(object)
371
Georg Brandl39cadc32010-10-15 16:53:24 +0000372 Return true if the object is a built-in function or a bound built-in method.
Georg Brandl116aa622007-08-15 14:28:22 +0000373
374
375.. function:: isroutine(object)
376
377 Return true if the object is a user-defined or built-in function or method.
378
Georg Brandl39cadc32010-10-15 16:53:24 +0000379
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000380.. function:: isabstract(object)
381
382 Return true if the object is an abstract base class.
383
Georg Brandl116aa622007-08-15 14:28:22 +0000384
385.. function:: ismethoddescriptor(object)
386
Georg Brandl39cadc32010-10-15 16:53:24 +0000387 Return true if the object is a method descriptor, but not if
388 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
389 are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000390
Georg Brandle6bcc912008-05-12 18:05:20 +0000391 This, for example, is true of ``int.__add__``. An object passing this test
Martin Panterbae5d812016-06-18 03:57:31 +0000392 has a :meth:`~object.__get__` method but not a :meth:`~object.__set__`
393 method, but beyond that the set of attributes varies. A
394 :attr:`~definition.__name__` attribute is usually
Georg Brandle6bcc912008-05-12 18:05:20 +0000395 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000396
Georg Brandl9afde1c2007-11-01 20:32:30 +0000397 Methods implemented via descriptors that also pass one of the other tests
398 return false from the :func:`ismethoddescriptor` test, simply because the
399 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000400 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402
403.. function:: isdatadescriptor(object)
404
405 Return true if the object is a data descriptor.
406
Martin Panterbae5d812016-06-18 03:57:31 +0000407 Data descriptors have both a :attr:`~object.__get__` and a :attr:`~object.__set__` method.
Georg Brandl9afde1c2007-11-01 20:32:30 +0000408 Examples are properties (defined in Python), getsets, and members. The
409 latter two are defined in C and there are more specific tests available for
410 those types, which is robust across Python implementations. Typically, data
Martin Panterbae5d812016-06-18 03:57:31 +0000411 descriptors will also have :attr:`~definition.__name__` and :attr:`__doc__` attributes
Georg Brandl9afde1c2007-11-01 20:32:30 +0000412 (properties, getsets, and members have both of these attributes), but this is
413 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000414
Georg Brandl116aa622007-08-15 14:28:22 +0000415
416.. function:: isgetsetdescriptor(object)
417
418 Return true if the object is a getset descriptor.
419
Georg Brandl495f7b52009-10-27 15:28:25 +0000420 .. impl-detail::
421
422 getsets are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000423 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000424 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000425
Georg Brandl116aa622007-08-15 14:28:22 +0000426
427.. function:: ismemberdescriptor(object)
428
429 Return true if the object is a member descriptor.
430
Georg Brandl495f7b52009-10-27 15:28:25 +0000431 .. impl-detail::
432
433 Member descriptors are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000434 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000435 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000436
Georg Brandl116aa622007-08-15 14:28:22 +0000437
438.. _inspect-source:
439
440Retrieving source code
441----------------------
442
Georg Brandl116aa622007-08-15 14:28:22 +0000443.. function:: getdoc(object)
444
Georg Brandl0c77a822008-06-10 16:37:50 +0000445 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300446 If the documentation string for an object is not provided and the object is
447 a class, a method, a property or a descriptor, retrieve the documentation
448 string from the inheritance hierarchy.
Georg Brandl116aa622007-08-15 14:28:22 +0000449
Berker Peksag4333d8b2015-07-30 18:06:09 +0300450 .. versionchanged:: 3.5
451 Documentation strings are now inherited if not overridden.
452
Georg Brandl116aa622007-08-15 14:28:22 +0000453
454.. function:: getcomments(object)
455
456 Return in a single string any lines of comments immediately preceding the
457 object's source code (for a class, function, or method), or at the top of the
Marco Buttu3f2155f2017-03-17 09:50:23 +0100458 Python source file (if the object is a module). If the object's source code
459 is unavailable, return ``None``. This could happen if the object has been
460 defined in C or the interactive shell.
Georg Brandl116aa622007-08-15 14:28:22 +0000461
462
463.. function:: getfile(object)
464
465 Return the name of the (text or binary) file in which an object was defined.
466 This will fail with a :exc:`TypeError` if the object is a built-in module,
467 class, or function.
468
469
470.. function:: getmodule(object)
471
472 Try to guess which module an object was defined in.
473
474
475.. function:: getsourcefile(object)
476
477 Return the name of the Python source file in which an object was defined. This
478 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
479 function.
480
481
482.. function:: getsourcelines(object)
483
484 Return a list of source lines and starting line number for an object. The
485 argument may be a module, class, method, function, traceback, frame, or code
486 object. The source code is returned as a list of the lines corresponding to the
487 object and the line number indicates where in the original source file the first
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200488 line of code was found. An :exc:`OSError` is raised if the source code cannot
Georg Brandl116aa622007-08-15 14:28:22 +0000489 be retrieved.
490
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200491 .. versionchanged:: 3.3
492 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
493 former.
494
Georg Brandl116aa622007-08-15 14:28:22 +0000495
496.. function:: getsource(object)
497
498 Return the text of the source code for an object. The argument may be a module,
499 class, method, function, traceback, frame, or code object. The source code is
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200500 returned as a single string. An :exc:`OSError` is raised if the source code
Georg Brandl116aa622007-08-15 14:28:22 +0000501 cannot be retrieved.
502
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200503 .. versionchanged:: 3.3
504 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
505 former.
506
Georg Brandl116aa622007-08-15 14:28:22 +0000507
Georg Brandl0c77a822008-06-10 16:37:50 +0000508.. function:: cleandoc(doc)
509
510 Clean up indentation from docstrings that are indented to line up with blocks
Senthil Kumaranebd84e32016-05-29 20:36:58 -0700511 of code.
512
513 All leading whitespace is removed from the first line. Any leading whitespace
514 that can be uniformly removed from the second line onwards is removed. Empty
515 lines at the beginning and end are subsequently removed. Also, all tabs are
516 expanded to spaces.
Georg Brandl0c77a822008-06-10 16:37:50 +0000517
Georg Brandl0c77a822008-06-10 16:37:50 +0000518
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300519.. _inspect-signature-object:
520
Georg Brandle4717722012-08-14 09:45:28 +0200521Introspecting callables with the Signature object
522-------------------------------------------------
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300523
524.. versionadded:: 3.3
525
Georg Brandle4717722012-08-14 09:45:28 +0200526The Signature object represents the call signature of a callable object and its
527return annotation. To retrieve a Signature object, use the :func:`signature`
528function.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300529
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400530.. function:: signature(callable, \*, follow_wrapped=True)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300531
Georg Brandle4717722012-08-14 09:45:28 +0200532 Return a :class:`Signature` object for the given ``callable``::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300533
534 >>> from inspect import signature
535 >>> def foo(a, *, b:int, **kwargs):
536 ... pass
537
538 >>> sig = signature(foo)
539
540 >>> str(sig)
541 '(a, *, b:int, **kwargs)'
542
543 >>> str(sig.parameters['b'])
544 'b:int'
545
546 >>> sig.parameters['b'].annotation
547 <class 'int'>
548
Georg Brandle4717722012-08-14 09:45:28 +0200549 Accepts a wide range of python callables, from plain functions and classes to
550 :func:`functools.partial` objects.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300551
Larry Hastings5c661892014-01-24 06:17:25 -0800552 Raises :exc:`ValueError` if no signature can be provided, and
553 :exc:`TypeError` if that type of object is not supported.
554
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400555 .. versionadded:: 3.5
556 ``follow_wrapped`` parameter. Pass ``False`` to get a signature of
557 ``callable`` specifically (``callable.__wrapped__`` will not be used to
558 unwrap decorated callables.)
559
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300560 .. note::
561
Georg Brandle4717722012-08-14 09:45:28 +0200562 Some callables may not be introspectable in certain implementations of
Yury Selivanovd71e52f2014-01-30 00:22:57 -0500563 Python. For example, in CPython, some built-in functions defined in
564 C provide no metadata about their arguments.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300565
566
Yury Selivanov78356892014-01-30 00:10:54 -0500567.. class:: Signature(parameters=None, \*, return_annotation=Signature.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300568
Georg Brandle4717722012-08-14 09:45:28 +0200569 A Signature object represents the call signature of a function and its return
570 annotation. For each parameter accepted by the function it stores a
571 :class:`Parameter` object in its :attr:`parameters` collection.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300572
Yury Selivanov78356892014-01-30 00:10:54 -0500573 The optional *parameters* argument is a sequence of :class:`Parameter`
574 objects, which is validated to check that there are no parameters with
575 duplicate names, and that the parameters are in the right order, i.e.
576 positional-only first, then positional-or-keyword, and that parameters with
577 defaults follow parameters without defaults.
578
579 The optional *return_annotation* argument, can be an arbitrary Python object,
580 is the "return" annotation of the callable.
581
Georg Brandle4717722012-08-14 09:45:28 +0200582 Signature objects are *immutable*. Use :meth:`Signature.replace` to make a
583 modified copy.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300584
Yury Selivanov67d727e2014-03-29 13:24:14 -0400585 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400586 Signature objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400587
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300588 .. attribute:: Signature.empty
589
590 A special class-level marker to specify absence of a return annotation.
591
592 .. attribute:: Signature.parameters
593
594 An ordered mapping of parameters' names to the corresponding
595 :class:`Parameter` objects.
596
597 .. attribute:: Signature.return_annotation
598
Georg Brandle4717722012-08-14 09:45:28 +0200599 The "return" annotation for the callable. If the callable has no "return"
600 annotation, this attribute is set to :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300601
602 .. method:: Signature.bind(*args, **kwargs)
603
Georg Brandle4717722012-08-14 09:45:28 +0200604 Create a mapping from positional and keyword arguments to parameters.
605 Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
606 signature, or raises a :exc:`TypeError`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300607
608 .. method:: Signature.bind_partial(*args, **kwargs)
609
Georg Brandle4717722012-08-14 09:45:28 +0200610 Works the same way as :meth:`Signature.bind`, but allows the omission of
611 some required arguments (mimics :func:`functools.partial` behavior.)
612 Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
613 passed arguments do not match the signature.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300614
Ezio Melotti8429b672012-09-14 06:35:09 +0300615 .. method:: Signature.replace(*[, parameters][, return_annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300616
Georg Brandle4717722012-08-14 09:45:28 +0200617 Create a new Signature instance based on the instance replace was invoked
618 on. It is possible to pass different ``parameters`` and/or
619 ``return_annotation`` to override the corresponding properties of the base
620 signature. To remove return_annotation from the copied Signature, pass in
621 :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300622
623 ::
624
625 >>> def test(a, b):
626 ... pass
627 >>> sig = signature(test)
628 >>> new_sig = sig.replace(return_annotation="new return anno")
629 >>> str(new_sig)
630 "(a, b) -> 'new return anno'"
631
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400632 .. classmethod:: Signature.from_callable(obj, \*, follow_wrapped=True)
Yury Selivanovda396452014-03-27 12:09:24 -0400633
634 Return a :class:`Signature` (or its subclass) object for a given callable
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400635 ``obj``. Pass ``follow_wrapped=False`` to get a signature of ``obj``
636 without unwrapping its ``__wrapped__`` chain.
Yury Selivanovda396452014-03-27 12:09:24 -0400637
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400638 This method simplifies subclassing of :class:`Signature`::
Yury Selivanovda396452014-03-27 12:09:24 -0400639
640 class MySignature(Signature):
641 pass
642 sig = MySignature.from_callable(min)
643 assert isinstance(sig, MySignature)
644
Yury Selivanov232b9342014-03-29 13:18:30 -0400645 .. versionadded:: 3.5
646
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300647
Yury Selivanov78356892014-01-30 00:10:54 -0500648.. class:: Parameter(name, kind, \*, default=Parameter.empty, annotation=Parameter.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300649
Georg Brandle4717722012-08-14 09:45:28 +0200650 Parameter objects are *immutable*. Instead of modifying a Parameter object,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300651 you can use :meth:`Parameter.replace` to create a modified copy.
652
Yury Selivanov67d727e2014-03-29 13:24:14 -0400653 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400654 Parameter objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400655
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300656 .. attribute:: Parameter.empty
657
Georg Brandle4717722012-08-14 09:45:28 +0200658 A special class-level marker to specify absence of default values and
659 annotations.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300660
661 .. attribute:: Parameter.name
662
Yury Selivanov2393dca2014-01-27 15:07:58 -0500663 The name of the parameter as a string. The name must be a valid
664 Python identifier.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300665
Nick Coghlanb4b966e2016-06-04 14:40:03 -0700666 .. impl-detail::
667
668 CPython generates implicit parameter names of the form ``.0`` on the
669 code objects used to implement comprehensions and generator
670 expressions.
671
672 .. versionchanged:: 3.6
673 These parameter names are exposed by this module as names like
674 ``implicit0``.
675
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300676 .. attribute:: Parameter.default
677
Georg Brandle4717722012-08-14 09:45:28 +0200678 The default value for the parameter. If the parameter has no default
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300679 value, this attribute is set to :attr:`Parameter.empty`.
680
681 .. attribute:: Parameter.annotation
682
Georg Brandle4717722012-08-14 09:45:28 +0200683 The annotation for the parameter. If the parameter has no annotation,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300684 this attribute is set to :attr:`Parameter.empty`.
685
686 .. attribute:: Parameter.kind
687
Georg Brandle4717722012-08-14 09:45:28 +0200688 Describes how argument values are bound to the parameter. Possible values
689 (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300690
Georg Brandl44ea77b2013-03-28 13:28:44 +0100691 .. tabularcolumns:: |l|L|
692
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300693 +------------------------+----------------------------------------------+
694 | Name | Meaning |
695 +========================+==============================================+
696 | *POSITIONAL_ONLY* | Value must be supplied as a positional |
697 | | argument. |
698 | | |
699 | | Python has no explicit syntax for defining |
700 | | positional-only parameters, but many built-in|
701 | | and extension module functions (especially |
702 | | those that accept only one or two parameters)|
703 | | accept them. |
704 +------------------------+----------------------------------------------+
705 | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
706 | | positional argument (this is the standard |
707 | | binding behaviour for functions implemented |
708 | | in Python.) |
709 +------------------------+----------------------------------------------+
710 | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
711 | | bound to any other parameter. This |
712 | | corresponds to a ``*args`` parameter in a |
713 | | Python function definition. |
714 +------------------------+----------------------------------------------+
715 | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
716 | | Keyword only parameters are those which |
717 | | appear after a ``*`` or ``*args`` entry in a |
718 | | Python function definition. |
719 +------------------------+----------------------------------------------+
720 | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
721 | | to any other parameter. This corresponds to a|
722 | | ``**kwargs`` parameter in a Python function |
723 | | definition. |
724 +------------------------+----------------------------------------------+
725
Andrew Svetloveed18082012-08-13 18:23:54 +0300726 Example: print all keyword-only arguments without default values::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300727
728 >>> def foo(a, b, *, c, d=10):
729 ... pass
730
731 >>> sig = signature(foo)
732 >>> for param in sig.parameters.values():
733 ... if (param.kind == param.KEYWORD_ONLY and
734 ... param.default is param.empty):
735 ... print('Parameter:', param)
736 Parameter: c
737
Ezio Melotti8429b672012-09-14 06:35:09 +0300738 .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300739
Georg Brandle4717722012-08-14 09:45:28 +0200740 Create a new Parameter instance based on the instance replaced was invoked
741 on. To override a :class:`Parameter` attribute, pass the corresponding
742 argument. To remove a default value or/and an annotation from a
743 Parameter, pass :attr:`Parameter.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300744
745 ::
746
747 >>> from inspect import Parameter
748 >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
749 >>> str(param)
750 'foo=42'
751
752 >>> str(param.replace()) # Will create a shallow copy of 'param'
753 'foo=42'
754
755 >>> str(param.replace(default=Parameter.empty, annotation='spam'))
756 "foo:'spam'"
757
Yury Selivanov2393dca2014-01-27 15:07:58 -0500758 .. versionchanged:: 3.4
759 In Python 3.3 Parameter objects were allowed to have ``name`` set
760 to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``.
761 This is no longer permitted.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300762
763.. class:: BoundArguments
764
765 Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
766 Holds the mapping of arguments to the function's parameters.
767
768 .. attribute:: BoundArguments.arguments
769
770 An ordered, mutable mapping (:class:`collections.OrderedDict`) of
Georg Brandle4717722012-08-14 09:45:28 +0200771 parameters' names to arguments' values. Contains only explicitly bound
772 arguments. Changes in :attr:`arguments` will reflect in :attr:`args` and
773 :attr:`kwargs`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300774
Georg Brandle4717722012-08-14 09:45:28 +0200775 Should be used in conjunction with :attr:`Signature.parameters` for any
776 argument processing purposes.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300777
778 .. note::
779
780 Arguments for which :meth:`Signature.bind` or
781 :meth:`Signature.bind_partial` relied on a default value are skipped.
Yury Selivanovb907a512015-05-16 13:45:09 -0400782 However, if needed, use :meth:`BoundArguments.apply_defaults` to add
783 them.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300784
785 .. attribute:: BoundArguments.args
786
Georg Brandle4717722012-08-14 09:45:28 +0200787 A tuple of positional arguments values. Dynamically computed from the
788 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300789
790 .. attribute:: BoundArguments.kwargs
791
Georg Brandle4717722012-08-14 09:45:28 +0200792 A dict of keyword arguments values. Dynamically computed from the
793 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300794
Yury Selivanov82796192015-05-14 14:14:02 -0400795 .. attribute:: BoundArguments.signature
796
797 A reference to the parent :class:`Signature` object.
798
Yury Selivanovb907a512015-05-16 13:45:09 -0400799 .. method:: BoundArguments.apply_defaults()
800
801 Set default values for missing arguments.
802
803 For variable-positional arguments (``*args``) the default is an
804 empty tuple.
805
806 For variable-keyword arguments (``**kwargs``) the default is an
807 empty dict.
808
809 ::
810
811 >>> def foo(a, b='ham', *args): pass
812 >>> ba = inspect.signature(foo).bind('spam')
813 >>> ba.apply_defaults()
814 >>> ba.arguments
815 OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])
816
Berker Peksag5b3df5b2015-05-16 23:29:31 +0300817 .. versionadded:: 3.5
818
Georg Brandle4717722012-08-14 09:45:28 +0200819 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
820 functions::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300821
822 def test(a, *, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300823 ...
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300824
825 sig = signature(test)
826 ba = sig.bind(10, b=20)
827 test(*ba.args, **ba.kwargs)
828
829
Georg Brandle4717722012-08-14 09:45:28 +0200830.. seealso::
831
832 :pep:`362` - Function Signature Object.
833 The detailed specification, implementation details and examples.
834
835
Georg Brandl116aa622007-08-15 14:28:22 +0000836.. _inspect-classes-functions:
837
838Classes and functions
839---------------------
840
Georg Brandl3dd33882009-06-01 17:35:27 +0000841.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000842
843 Arrange the given list of classes into a hierarchy of nested lists. Where a
844 nested list appears, it contains classes derived from the class whose entry
845 immediately precedes the list. Each entry is a 2-tuple containing a class and a
846 tuple of its base classes. If the *unique* argument is true, exactly one entry
847 appears in the returned structure for each class in the given list. Otherwise,
848 classes using multiple inheritance and their descendants will appear multiple
849 times.
850
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500851
852.. function:: getargspec(func)
853
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000854 Get the names and default values of a Python function's parameters. A
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500855 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000856 returned. *args* is a list of the parameter names. *varargs* and *keywords*
857 are the names of the ``*`` and ``**`` parameters or ``None``. *defaults* is a
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500858 tuple of default argument values or ``None`` if there are no default
859 arguments; if this tuple has *n* elements, they correspond to the last
860 *n* elements listed in *args*.
861
862 .. deprecated:: 3.0
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000863 Use :func:`getfullargspec` for an updated API that is usually a drop-in
864 replacement, but also correctly handles function annotations and
865 keyword-only parameters.
866
867 Alternatively, use :func:`signature` and
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500868 :ref:`Signature Object <inspect-signature-object>`, which provide a
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000869 more structured introspection API for callables.
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500870
871
Georg Brandl138bcb52007-09-12 19:04:21 +0000872.. function:: getfullargspec(func)
873
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000874 Get the names and default values of a Python function's parameters. A
Georg Brandl82402752010-01-09 09:48:46 +0000875 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000876
Georg Brandl3dd33882009-06-01 17:35:27 +0000877 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
878 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000879
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000880 *args* is a list of the positional parameter names.
881 *varargs* is the name of the ``*`` parameter or ``None`` if arbitrary
882 positional arguments are not accepted.
883 *varkw* is the name of the ``**`` parameter or ``None`` if arbitrary
884 keyword arguments are not accepted.
885 *defaults* is an *n*-tuple of default argument values corresponding to the
886 last *n* positional parameters, or ``None`` if there are no such defaults
887 defined.
888 *kwonlyargs* is a list of keyword-only parameter names.
889 *kwonlydefaults* is a dictionary mapping parameter names from *kwonlyargs*
890 to the default values used if no argument is supplied.
891 *annotations* is a dictionary mapping parameter names to annotations.
892 The special key ``"return"`` is used to report the function return value
893 annotation (if any).
894
895 Note that :func:`signature` and
896 :ref:`Signature Object <inspect-signature-object>` provide the recommended
897 API for callable introspection, and support additional behaviours (like
898 positional-only arguments) that are sometimes encountered in extension module
899 APIs. This function is retained primarily for use in code that needs to
900 maintain compatibility with the Python 2 ``inspect`` module API.
Georg Brandl138bcb52007-09-12 19:04:21 +0000901
Nick Coghlan16355782014-03-08 16:36:37 +1000902 .. versionchanged:: 3.4
903 This function is now based on :func:`signature`, but still ignores
904 ``__wrapped__`` attributes and includes the already bound first
905 parameter in the signature output for bound methods.
906
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000907 .. versionchanged:: 3.6
908 This method was previously documented as deprecated in favour of
909 :func:`signature` in Python 3.5, but that decision has been reversed
910 in order to restore a clearly supported standard interface for
911 single-source Python 2/3 code migrating away from the legacy
912 :func:`getargspec` API.
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400913
Georg Brandl116aa622007-08-15 14:28:22 +0000914
915.. function:: getargvalues(frame)
916
Georg Brandl3dd33882009-06-01 17:35:27 +0000917 Get information about arguments passed into a particular frame. A
918 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000919 returned. *args* is a list of the argument names. *varargs* and *keywords*
920 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000921 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000922
Matthias Bussonnier0899b982017-02-21 21:45:51 -0800923 .. note::
924 This function was inadvertently marked as deprecated in Python 3.5.
Yury Selivanov945fff42015-05-22 16:28:05 -0400925
Georg Brandl116aa622007-08-15 14:28:22 +0000926
Andrew Svetlov735d3172012-10-27 00:28:20 +0300927.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Georg Brandl116aa622007-08-15 14:28:22 +0000928
Michael Foord3af125a2012-04-21 18:22:28 +0100929 Format a pretty argument spec from the values returned by
Berker Peksagfa3922c2015-07-31 04:11:29 +0300930 :func:`getfullargspec`.
Michael Foord3af125a2012-04-21 18:22:28 +0100931
932 The first seven arguments are (``args``, ``varargs``, ``varkw``,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100933 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
Andrew Svetlov735d3172012-10-27 00:28:20 +0300934
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100935 The other six arguments are functions that are called to turn argument names,
936 ``*`` argument name, ``**`` argument name, default values, return annotation
937 and individual annotations into strings, respectively.
938
939 For example:
940
941 >>> from inspect import formatargspec, getfullargspec
942 >>> def f(a: int, b: float):
943 ... pass
944 ...
945 >>> formatargspec(*getfullargspec(f))
946 '(a: int, b: float)'
Georg Brandl116aa622007-08-15 14:28:22 +0000947
Yury Selivanov945fff42015-05-22 16:28:05 -0400948 .. deprecated:: 3.5
949 Use :func:`signature` and
950 :ref:`Signature Object <inspect-signature-object>`, which provide a
951 better introspecting API for callables.
952
Georg Brandl116aa622007-08-15 14:28:22 +0000953
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000954.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000955
956 Format a pretty argument spec from the four values returned by
957 :func:`getargvalues`. The format\* arguments are the corresponding optional
958 formatting functions that are called to turn names and values into strings.
959
Matthias Bussonnier0899b982017-02-21 21:45:51 -0800960 .. note::
961 This function was inadvertently marked as deprecated in Python 3.5.
Yury Selivanov945fff42015-05-22 16:28:05 -0400962
Georg Brandl116aa622007-08-15 14:28:22 +0000963
964.. function:: getmro(cls)
965
966 Return a tuple of class cls's base classes, including cls, in method resolution
967 order. No class appears more than once in this tuple. Note that the method
968 resolution order depends on cls's type. Unless a very peculiar user-defined
969 metatype is in use, cls will be the first element of the tuple.
970
971
Benjamin Peterson3a990c62014-01-02 12:22:30 -0600972.. function:: getcallargs(func, *args, **kwds)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000973
974 Bind the *args* and *kwds* to the argument names of the Python function or
975 method *func*, as if it was called with them. For bound methods, bind also the
976 first argument (typically named ``self``) to the associated instance. A dict
977 is returned, mapping the argument names (including the names of the ``*`` and
978 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
979 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
980 an exception because of incompatible signature, an exception of the same type
981 and the same or similar message is raised. For example::
982
983 >>> from inspect import getcallargs
984 >>> def f(a, b=1, *pos, **named):
985 ... pass
Andrew Svetlove939f382012-08-09 13:25:32 +0300986 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
987 True
988 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
989 True
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000990 >>> getcallargs(f)
991 Traceback (most recent call last):
992 ...
Andrew Svetlove939f382012-08-09 13:25:32 +0300993 TypeError: f() missing 1 required positional argument: 'a'
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000994
995 .. versionadded:: 3.2
996
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400997 .. deprecated:: 3.5
998 Use :meth:`Signature.bind` and :meth:`Signature.bind_partial` instead.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300999
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001000
Nick Coghlan2f92e542012-06-23 19:39:55 +10001001.. function:: getclosurevars(func)
1002
1003 Get the mapping of external name references in a Python function or
1004 method *func* to their current values. A
1005 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
1006 is returned. *nonlocals* maps referenced names to lexical closure
1007 variables, *globals* to the function's module globals and *builtins* to
1008 the builtins visible from the function body. *unbound* is the set of names
1009 referenced in the function that could not be resolved at all given the
1010 current module globals and builtins.
1011
1012 :exc:`TypeError` is raised if *func* is not a Python function or method.
1013
1014 .. versionadded:: 3.3
1015
1016
Nick Coghlane8c45d62013-07-28 20:00:01 +10001017.. function:: unwrap(func, *, stop=None)
1018
1019 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
1020 attributes returning the last object in the chain.
1021
1022 *stop* is an optional callback accepting an object in the wrapper chain
1023 as its sole argument that allows the unwrapping to be terminated early if
1024 the callback returns a true value. If the callback never returns a true
1025 value, the last object in the chain is returned as usual. For example,
1026 :func:`signature` uses this to stop unwrapping if any object in the
1027 chain has a ``__signature__`` attribute defined.
1028
1029 :exc:`ValueError` is raised if a cycle is encountered.
1030
1031 .. versionadded:: 3.4
1032
1033
Georg Brandl116aa622007-08-15 14:28:22 +00001034.. _inspect-stack:
1035
1036The interpreter stack
1037---------------------
1038
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001039When the following functions return "frame records," each record is a
1040:term:`named tuple`
1041``FrameInfo(frame, filename, lineno, function, code_context, index)``.
1042The tuple contains the frame object, the filename, the line number of the
1043current line,
Georg Brandl116aa622007-08-15 14:28:22 +00001044the function name, a list of lines of context from the source code, and the
1045index of the current line within that list.
1046
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001047.. versionchanged:: 3.5
1048 Return a named tuple instead of a tuple.
1049
Georg Brandle720c0a2009-04-27 16:20:50 +00001050.. note::
Georg Brandl116aa622007-08-15 14:28:22 +00001051
1052 Keeping references to frame objects, as found in the first element of the frame
1053 records these functions return, can cause your program to create reference
1054 cycles. Once a reference cycle has been created, the lifespan of all objects
1055 which can be accessed from the objects which form the cycle can become much
1056 longer even if Python's optional cycle detector is enabled. If such cycles must
1057 be created, it is important to ensure they are explicitly broken to avoid the
1058 delayed destruction of objects and increased memory consumption which occurs.
1059
1060 Though the cycle detector will catch these, destruction of the frames (and local
1061 variables) can be made deterministic by removing the cycle in a
1062 :keyword:`finally` clause. This is also important if the cycle detector was
1063 disabled when Python was compiled or using :func:`gc.disable`. For example::
1064
1065 def handle_stackframe_without_leak():
1066 frame = inspect.currentframe()
1067 try:
1068 # do something with the frame
1069 finally:
1070 del frame
1071
Antoine Pitrou58720d62013-08-05 23:26:40 +02001072 If you want to keep the frame around (for example to print a traceback
1073 later), you can also break reference cycles by using the
1074 :meth:`frame.clear` method.
1075
Georg Brandl116aa622007-08-15 14:28:22 +00001076The optional *context* argument supported by most of these functions specifies
1077the number of lines of context to return, which are centered around the current
1078line.
1079
1080
Georg Brandl3dd33882009-06-01 17:35:27 +00001081.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001082
Georg Brandl48310cd2009-01-03 21:18:54 +00001083 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +00001084 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +00001085
1086
Georg Brandl3dd33882009-06-01 17:35:27 +00001087.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001088
1089 Get a list of frame records for a frame and all outer frames. These frames
1090 represent the calls that lead to the creation of *frame*. The first entry in the
1091 returned list represents *frame*; the last entry represents the outermost call
1092 on *frame*'s stack.
1093
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001094 .. versionchanged:: 3.5
1095 A list of :term:`named tuples <named tuple>`
1096 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1097 is returned.
1098
Georg Brandl116aa622007-08-15 14:28:22 +00001099
Georg Brandl3dd33882009-06-01 17:35:27 +00001100.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001101
1102 Get a list of frame records for a traceback's frame and all inner frames. These
1103 frames represent calls made as a consequence of *frame*. The first entry in the
1104 list represents *traceback*; the last entry represents where the exception was
1105 raised.
1106
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001107 .. versionchanged:: 3.5
1108 A list of :term:`named tuples <named tuple>`
1109 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1110 is returned.
1111
Georg Brandl116aa622007-08-15 14:28:22 +00001112
1113.. function:: currentframe()
1114
1115 Return the frame object for the caller's stack frame.
1116
Georg Brandl495f7b52009-10-27 15:28:25 +00001117 .. impl-detail::
1118
1119 This function relies on Python stack frame support in the interpreter,
1120 which isn't guaranteed to exist in all implementations of Python. If
1121 running in an implementation without Python stack frame support this
1122 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001123
Georg Brandl116aa622007-08-15 14:28:22 +00001124
Georg Brandl3dd33882009-06-01 17:35:27 +00001125.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001126
1127 Return a list of frame records for the caller's stack. The first entry in the
1128 returned list represents the caller; the last entry represents the outermost
1129 call on the stack.
1130
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001131 .. versionchanged:: 3.5
1132 A list of :term:`named tuples <named tuple>`
1133 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1134 is returned.
1135
Georg Brandl116aa622007-08-15 14:28:22 +00001136
Georg Brandl3dd33882009-06-01 17:35:27 +00001137.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001138
1139 Return a list of frame records for the stack between the current frame and the
1140 frame in which an exception currently being handled was raised in. The first
1141 entry in the list represents the caller; the last entry represents where the
1142 exception was raised.
1143
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001144 .. versionchanged:: 3.5
1145 A list of :term:`named tuples <named tuple>`
1146 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1147 is returned.
1148
Michael Foord95fc51d2010-11-20 15:07:30 +00001149
1150Fetching attributes statically
1151------------------------------
1152
1153Both :func:`getattr` and :func:`hasattr` can trigger code execution when
1154fetching or checking for the existence of attributes. Descriptors, like
1155properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
1156may be called.
1157
1158For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +02001159can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +00001160but avoids executing code when it fetches attributes.
1161
1162.. function:: getattr_static(obj, attr, default=None)
1163
1164 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +02001165 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +00001166
1167 Note: this function may not be able to retrieve all attributes
1168 that getattr can fetch (like dynamically created attributes)
1169 and may find attributes that getattr can't (like descriptors
1170 that raise AttributeError). It can also return descriptors objects
1171 instead of instance members.
1172
Serhiy Storchakabfdcd432013-10-13 23:09:14 +03001173 If the instance :attr:`~object.__dict__` is shadowed by another member (for
1174 example a property) then this function will be unable to find instance
1175 members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001176
Michael Foorddcebe0f2011-03-15 19:20:44 -04001177 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +00001178
Éric Araujo941afed2011-09-01 02:47:34 +02001179:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +00001180getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +00001181is returned instead of the underlying attribute.
1182
1183You can handle these with code like the following. Note that
1184for arbitrary getset descriptors invoking these may trigger
1185code execution::
1186
1187 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +00001188 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +00001189 __slots__ = ['foo']
1190
1191 slot_descriptor = type(_foo.foo)
1192 getset_descriptor = type(type(open(__file__)).name)
1193 wrapper_descriptor = type(str.__dict__['__add__'])
1194 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
1195
1196 result = getattr_static(some_object, 'foo')
1197 if type(result) in descriptor_types:
1198 try:
1199 result = result.__get__()
1200 except AttributeError:
1201 # descriptors can raise AttributeError to
1202 # indicate there is no underlying value
1203 # in which case the descriptor itself will
1204 # have to do
1205 pass
Nick Coghlane0f04652010-11-21 03:44:04 +00001206
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001207
Yury Selivanov5376ba92015-06-22 12:19:30 -04001208Current State of Generators and Coroutines
1209------------------------------------------
Nick Coghlane0f04652010-11-21 03:44:04 +00001210
1211When implementing coroutine schedulers and for other advanced uses of
1212generators, it is useful to determine whether a generator is currently
1213executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001214terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +00001215generator to be determined easily.
1216
1217.. function:: getgeneratorstate(generator)
1218
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001219 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +00001220
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001221 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +00001222 * GEN_CREATED: Waiting to start execution.
1223 * GEN_RUNNING: Currently being executed by the interpreter.
1224 * GEN_SUSPENDED: Currently suspended at a yield expression.
1225 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +00001226
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001227 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001228
Yury Selivanov5376ba92015-06-22 12:19:30 -04001229.. function:: getcoroutinestate(coroutine)
1230
1231 Get current state of a coroutine object. The function is intended to be
1232 used with coroutine objects created by :keyword:`async def` functions, but
1233 will accept any coroutine-like object that has ``cr_running`` and
1234 ``cr_frame`` attributes.
1235
1236 Possible states are:
1237 * CORO_CREATED: Waiting to start execution.
1238 * CORO_RUNNING: Currently being executed by the interpreter.
1239 * CORO_SUSPENDED: Currently suspended at an await expression.
1240 * CORO_CLOSED: Execution has completed.
1241
1242 .. versionadded:: 3.5
1243
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001244The current internal state of the generator can also be queried. This is
1245mostly useful for testing purposes, to ensure that internal state is being
1246updated as expected:
1247
1248.. function:: getgeneratorlocals(generator)
1249
1250 Get the mapping of live local variables in *generator* to their current
1251 values. A dictionary is returned that maps from variable names to values.
1252 This is the equivalent of calling :func:`locals` in the body of the
1253 generator, and all the same caveats apply.
1254
1255 If *generator* is a :term:`generator` with no currently associated frame,
1256 then an empty dictionary is returned. :exc:`TypeError` is raised if
1257 *generator* is not a Python generator object.
1258
1259 .. impl-detail::
1260
1261 This function relies on the generator exposing a Python stack frame
1262 for introspection, which isn't guaranteed to be the case in all
1263 implementations of Python. In such cases, this function will always
1264 return an empty dictionary.
1265
1266 .. versionadded:: 3.3
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001267
Yury Selivanov5376ba92015-06-22 12:19:30 -04001268.. function:: getcoroutinelocals(coroutine)
1269
1270 This function is analogous to :func:`~inspect.getgeneratorlocals`, but
1271 works for coroutine objects created by :keyword:`async def` functions.
1272
1273 .. versionadded:: 3.5
1274
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001275
Yury Selivanovea75a512016-10-20 13:06:30 -04001276.. _inspect-module-co-flags:
1277
1278Code Objects Bit Flags
1279----------------------
1280
1281Python code objects have a ``co_flags`` attribute, which is a bitmap of
1282the following flags:
1283
Xiang Zhanga6902e62017-04-13 10:38:28 +08001284.. data:: CO_OPTIMIZED
1285
1286 The code object is optimized, using fast locals.
1287
Yury Selivanovea75a512016-10-20 13:06:30 -04001288.. data:: CO_NEWLOCALS
1289
1290 If set, a new dict will be created for the frame's ``f_locals`` when
1291 the code object is executed.
1292
1293.. data:: CO_VARARGS
1294
1295 The code object has a variable positional parameter (``*args``-like).
1296
1297.. data:: CO_VARKEYWORDS
1298
1299 The code object has a variable keyword parameter (``**kwargs``-like).
1300
Xiang Zhanga6902e62017-04-13 10:38:28 +08001301.. data:: CO_NESTED
1302
1303 The flag is set when the code object is a nested function.
1304
Yury Selivanovea75a512016-10-20 13:06:30 -04001305.. data:: CO_GENERATOR
1306
1307 The flag is set when the code object is a generator function, i.e.
1308 a generator object is returned when the code object is executed.
1309
1310.. data:: CO_NOFREE
1311
1312 The flag is set if there are no free or cell variables.
1313
1314.. data:: CO_COROUTINE
1315
Yury Selivanovb738a1f2016-10-20 16:30:51 -04001316 The flag is set when the code object is a coroutine function.
1317 When the code object is executed it returns a coroutine object.
1318 See :pep:`492` for more details.
Yury Selivanovea75a512016-10-20 13:06:30 -04001319
1320 .. versionadded:: 3.5
1321
1322.. data:: CO_ITERABLE_COROUTINE
1323
Yury Selivanovb738a1f2016-10-20 16:30:51 -04001324 The flag is used to transform generators into generator-based
1325 coroutines. Generator objects with this flag can be used in
1326 ``await`` expression, and can ``yield from`` coroutine objects.
1327 See :pep:`492` for more details.
Yury Selivanovea75a512016-10-20 13:06:30 -04001328
1329 .. versionadded:: 3.5
1330
Yury Selivanove20fed92016-10-20 13:11:34 -04001331.. data:: CO_ASYNC_GENERATOR
1332
Yury Selivanovb738a1f2016-10-20 16:30:51 -04001333 The flag is set when the code object is an asynchronous generator
1334 function. When the code object is executed it returns an
1335 asynchronous generator object. See :pep:`525` for more details.
Yury Selivanove20fed92016-10-20 13:11:34 -04001336
1337 .. versionadded:: 3.6
1338
Yury Selivanovea75a512016-10-20 13:06:30 -04001339.. note::
1340 The flags are specific to CPython, and may not be defined in other
1341 Python implementations. Furthermore, the flags are an implementation
1342 detail, and can be removed or deprecated in future Python releases.
1343 It's recommended to use public APIs from the :mod:`inspect` module
1344 for any introspection needs.
1345
1346
Nick Coghlan367df122013-10-27 01:57:34 +10001347.. _inspect-module-cli:
1348
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001349Command Line Interface
1350----------------------
1351
1352The :mod:`inspect` module also provides a basic introspection capability
1353from the command line.
1354
1355.. program:: inspect
1356
1357By default, accepts the name of a module and prints the source of that
1358module. A class or function within the module can be printed instead by
1359appended a colon and the qualified name of the target object.
1360
1361.. cmdoption:: --details
1362
1363 Print information about the specified object rather than the source code