blob: 147e802cac4be6ff98df59215746f502e176281d [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+-----------+-------------------+---------------------------+
73| function | __doc__ | documentation string |
74+-----------+-------------------+---------------------------+
75| | __name__ | name with which this |
76| | | function was defined |
77+-----------+-------------------+---------------------------+
78| | __qualname__ | qualified name |
79+-----------+-------------------+---------------------------+
80| | __code__ | code object containing |
81| | | compiled function |
82| | | :term:`bytecode` |
83+-----------+-------------------+---------------------------+
84| | __defaults__ | tuple of any default |
85| | | values for positional or |
86| | | keyword parameters |
87+-----------+-------------------+---------------------------+
88| | __kwdefaults__ | mapping of any default |
89| | | values for keyword-only |
90| | | parameters |
91+-----------+-------------------+---------------------------+
92| | __globals__ | global namespace in which |
93| | | this function was defined |
94+-----------+-------------------+---------------------------+
95| | __annotations__ | mapping of parameters |
96| | | names to annotations; |
97| | | ``"return"`` key is |
98| | | reserved for return |
99| | | annotations. |
100+-----------+-------------------+---------------------------+
101| traceback | tb_frame | frame object at this |
102| | | level |
103+-----------+-------------------+---------------------------+
104| | tb_lasti | index of last attempted |
105| | | instruction in bytecode |
106+-----------+-------------------+---------------------------+
107| | tb_lineno | current line number in |
108| | | Python source code |
109+-----------+-------------------+---------------------------+
110| | tb_next | next inner traceback |
111| | | object (called by this |
112| | | level) |
113+-----------+-------------------+---------------------------+
114| frame | f_back | next outer frame object |
115| | | (this frame's caller) |
116+-----------+-------------------+---------------------------+
117| | f_builtins | builtins namespace seen |
118| | | by this frame |
119+-----------+-------------------+---------------------------+
120| | f_code | code object being |
121| | | executed in this frame |
122+-----------+-------------------+---------------------------+
123| | f_globals | global namespace seen by |
124| | | this frame |
125+-----------+-------------------+---------------------------+
126| | f_lasti | index of last attempted |
127| | | instruction in bytecode |
128+-----------+-------------------+---------------------------+
129| | f_lineno | current line number in |
130| | | Python source code |
131+-----------+-------------------+---------------------------+
132| | f_locals | local namespace seen by |
133| | | this frame |
134+-----------+-------------------+---------------------------+
135| | f_restricted | 0 or 1 if frame is in |
136| | | restricted execution mode |
137+-----------+-------------------+---------------------------+
138| | f_trace | tracing function for this |
139| | | frame, or ``None`` |
140+-----------+-------------------+---------------------------+
141| code | co_argcount | number of arguments (not |
142| | | including keyword only |
143| | | arguments, \* or \*\* |
144| | | args) |
145+-----------+-------------------+---------------------------+
146| | co_code | string of raw compiled |
147| | | bytecode |
148+-----------+-------------------+---------------------------+
149| | co_cellvars | tuple of names of cell |
150| | | variables (referenced by |
151| | | containing scopes) |
152+-----------+-------------------+---------------------------+
153| | co_consts | tuple of constants used |
154| | | in the bytecode |
155+-----------+-------------------+---------------------------+
156| | co_filename | name of file in which |
157| | | this code object was |
158| | | created |
159+-----------+-------------------+---------------------------+
160| | co_firstlineno | number of first line in |
161| | | Python source code |
162+-----------+-------------------+---------------------------+
163| | co_flags | bitmap of ``CO_*`` flags, |
164| | | read more :ref:`here |
165| | | <inspect-module-co-flags>`|
166+-----------+-------------------+---------------------------+
167| | co_lnotab | encoded mapping of line |
168| | | numbers to bytecode |
169| | | indices |
170+-----------+-------------------+---------------------------+
171| | co_freevars | tuple of names of free |
172| | | variables (referenced via |
173| | | a function's closure) |
174+-----------+-------------------+---------------------------+
175| | co_kwonlyargcount | number of keyword only |
176| | | arguments (not including |
177| | | \*\* arg) |
178+-----------+-------------------+---------------------------+
179| | co_name | name with which this code |
180| | | object was defined |
181+-----------+-------------------+---------------------------+
182| | co_names | tuple of names of local |
183| | | variables |
184+-----------+-------------------+---------------------------+
185| | co_nlocals | number of local variables |
186+-----------+-------------------+---------------------------+
187| | co_stacksize | virtual machine stack |
188| | | space required |
189+-----------+-------------------+---------------------------+
190| | co_varnames | tuple of names of |
191| | | arguments and local |
192| | | variables |
193+-----------+-------------------+---------------------------+
194| generator | __name__ | name |
195+-----------+-------------------+---------------------------+
196| | __qualname__ | qualified name |
197+-----------+-------------------+---------------------------+
198| | gi_frame | frame |
199+-----------+-------------------+---------------------------+
200| | gi_running | is the generator running? |
201+-----------+-------------------+---------------------------+
202| | gi_code | code |
203+-----------+-------------------+---------------------------+
204| | gi_yieldfrom | object being iterated by |
205| | | ``yield from``, or |
206| | | ``None`` |
207+-----------+-------------------+---------------------------+
208| coroutine | __name__ | name |
209+-----------+-------------------+---------------------------+
210| | __qualname__ | qualified name |
211+-----------+-------------------+---------------------------+
212| | cr_await | object being awaited on, |
213| | | or ``None`` |
214+-----------+-------------------+---------------------------+
215| | cr_frame | frame |
216+-----------+-------------------+---------------------------+
217| | cr_running | is the coroutine running? |
218+-----------+-------------------+---------------------------+
219| | cr_code | code |
220+-----------+-------------------+---------------------------+
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800221| | cr_origin | where coroutine was |
222| | | created, or ``None``. See |
223| | | |coroutine-origin-link| |
224+-----------+-------------------+---------------------------+
Xiang Zhanga6902e62017-04-13 10:38:28 +0800225| builtin | __doc__ | documentation string |
226+-----------+-------------------+---------------------------+
227| | __name__ | original name of this |
228| | | function or method |
229+-----------+-------------------+---------------------------+
230| | __qualname__ | qualified name |
231+-----------+-------------------+---------------------------+
232| | __self__ | instance to which a |
233| | | method is bound, or |
234| | | ``None`` |
235+-----------+-------------------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000236
Victor Stinner40ee3012014-06-16 15:59:28 +0200237.. versionchanged:: 3.5
238
Yury Selivanov5fbad3c2015-08-17 13:04:41 -0400239 Add ``__qualname__`` and ``gi_yieldfrom`` attributes to generators.
240
241 The ``__name__`` attribute of generators is now set from the function
242 name, instead of the code name, and it can now be modified.
Victor Stinner40ee3012014-06-16 15:59:28 +0200243
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800244.. versionchanged:: 3.7
245
246 Add ``cr_origin`` attribute to coroutines.
Georg Brandl116aa622007-08-15 14:28:22 +0000247
248.. function:: getmembers(object[, predicate])
249
250 Return all the members of an object in a list of (name, value) pairs sorted by
251 name. If the optional *predicate* argument is supplied, only members for which
252 the predicate returns a true value are included.
253
Christian Heimes7f044312008-01-06 17:05:40 +0000254 .. note::
255
Ethan Furman63c141c2013-10-18 00:27:39 -0700256 :func:`getmembers` will only return class attributes defined in the
257 metaclass when the argument is a class and those attributes have been
258 listed in the metaclass' custom :meth:`__dir__`.
Christian Heimes7f044312008-01-06 17:05:40 +0000259
Georg Brandl116aa622007-08-15 14:28:22 +0000260
Georg Brandl116aa622007-08-15 14:28:22 +0000261.. function:: getmodulename(path)
262
263 Return the name of the module named by the file *path*, without including the
Nick Coghlan76e07702012-07-18 23:14:57 +1000264 names of enclosing packages. The file extension is checked against all of
265 the entries in :func:`importlib.machinery.all_suffixes`. If it matches,
266 the final path component is returned with the extension removed.
267 Otherwise, ``None`` is returned.
268
269 Note that this function *only* returns a meaningful name for actual
270 Python modules - paths that potentially refer to Python packages will
271 still return ``None``.
272
273 .. versionchanged:: 3.3
Yury Selivanov6dfbc5d2015-07-23 17:49:00 +0300274 The function is based directly on :mod:`importlib`.
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276
277.. function:: ismodule(object)
278
279 Return true if the object is a module.
280
281
282.. function:: isclass(object)
283
Georg Brandl39cadc32010-10-15 16:53:24 +0000284 Return true if the object is a class, whether built-in or created in Python
285 code.
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287
288.. function:: ismethod(object)
289
Georg Brandl39cadc32010-10-15 16:53:24 +0000290 Return true if the object is a bound method written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000291
292
293.. function:: isfunction(object)
294
Georg Brandl39cadc32010-10-15 16:53:24 +0000295 Return true if the object is a Python function, which includes functions
296 created by a :term:`lambda` expression.
Georg Brandl116aa622007-08-15 14:28:22 +0000297
298
Christian Heimes7131fd92008-02-19 14:21:46 +0000299.. function:: isgeneratorfunction(object)
300
301 Return true if the object is a Python generator function.
302
303
304.. function:: isgenerator(object)
305
306 Return true if the object is a generator.
307
308
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400309.. function:: iscoroutinefunction(object)
310
Yury Selivanov5376ba92015-06-22 12:19:30 -0400311 Return true if the object is a :term:`coroutine function`
312 (a function defined with an :keyword:`async def` syntax).
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400313
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400314 .. versionadded:: 3.5
315
316
317.. function:: iscoroutine(object)
318
Yury Selivanov5376ba92015-06-22 12:19:30 -0400319 Return true if the object is a :term:`coroutine` created by an
320 :keyword:`async def` function.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400321
322 .. versionadded:: 3.5
323
324
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400325.. function:: isawaitable(object)
326
327 Return true if the object can be used in :keyword:`await` expression.
328
329 Can also be used to distinguish generator-based coroutines from regular
330 generators::
331
332 def gen():
333 yield
334 @types.coroutine
335 def gen_coro():
336 yield
337
338 assert not isawaitable(gen())
339 assert isawaitable(gen_coro())
340
341 .. versionadded:: 3.5
342
343
Yury Selivanov03660042016-12-15 17:36:05 -0500344.. function:: isasyncgenfunction(object)
345
346 Return true if the object is an :term:`asynchronous generator` function,
347 for example::
348
349 >>> async def agen():
350 ... yield 1
351 ...
352 >>> inspect.isasyncgenfunction(agen)
353 True
354
355 .. versionadded:: 3.6
356
357
358.. function:: isasyncgen(object)
359
360 Return true if the object is an :term:`asynchronous generator iterator`
361 created by an :term:`asynchronous generator` function.
362
363 .. versionadded:: 3.6
364
Georg Brandl116aa622007-08-15 14:28:22 +0000365.. function:: istraceback(object)
366
367 Return true if the object is a traceback.
368
369
370.. function:: isframe(object)
371
372 Return true if the object is a frame.
373
374
375.. function:: iscode(object)
376
377 Return true if the object is a code.
378
379
380.. function:: isbuiltin(object)
381
Georg Brandl39cadc32010-10-15 16:53:24 +0000382 Return true if the object is a built-in function or a bound built-in method.
Georg Brandl116aa622007-08-15 14:28:22 +0000383
384
385.. function:: isroutine(object)
386
387 Return true if the object is a user-defined or built-in function or method.
388
Georg Brandl39cadc32010-10-15 16:53:24 +0000389
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000390.. function:: isabstract(object)
391
392 Return true if the object is an abstract base class.
393
Georg Brandl116aa622007-08-15 14:28:22 +0000394
395.. function:: ismethoddescriptor(object)
396
Georg Brandl39cadc32010-10-15 16:53:24 +0000397 Return true if the object is a method descriptor, but not if
398 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
399 are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000400
Georg Brandle6bcc912008-05-12 18:05:20 +0000401 This, for example, is true of ``int.__add__``. An object passing this test
Martin Panterbae5d812016-06-18 03:57:31 +0000402 has a :meth:`~object.__get__` method but not a :meth:`~object.__set__`
403 method, but beyond that the set of attributes varies. A
404 :attr:`~definition.__name__` attribute is usually
Georg Brandle6bcc912008-05-12 18:05:20 +0000405 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000406
Georg Brandl9afde1c2007-11-01 20:32:30 +0000407 Methods implemented via descriptors that also pass one of the other tests
408 return false from the :func:`ismethoddescriptor` test, simply because the
409 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000410 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000411
412
413.. function:: isdatadescriptor(object)
414
415 Return true if the object is a data descriptor.
416
Martin Panterbae5d812016-06-18 03:57:31 +0000417 Data descriptors have both a :attr:`~object.__get__` and a :attr:`~object.__set__` method.
Georg Brandl9afde1c2007-11-01 20:32:30 +0000418 Examples are properties (defined in Python), getsets, and members. The
419 latter two are defined in C and there are more specific tests available for
420 those types, which is robust across Python implementations. Typically, data
Martin Panterbae5d812016-06-18 03:57:31 +0000421 descriptors will also have :attr:`~definition.__name__` and :attr:`__doc__` attributes
Georg Brandl9afde1c2007-11-01 20:32:30 +0000422 (properties, getsets, and members have both of these attributes), but this is
423 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000424
Georg Brandl116aa622007-08-15 14:28:22 +0000425
426.. function:: isgetsetdescriptor(object)
427
428 Return true if the object is a getset descriptor.
429
Georg Brandl495f7b52009-10-27 15:28:25 +0000430 .. impl-detail::
431
432 getsets are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000433 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000434 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000435
Georg Brandl116aa622007-08-15 14:28:22 +0000436
437.. function:: ismemberdescriptor(object)
438
439 Return true if the object is a member descriptor.
440
Georg Brandl495f7b52009-10-27 15:28:25 +0000441 .. impl-detail::
442
443 Member descriptors are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000444 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000445 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000446
Georg Brandl116aa622007-08-15 14:28:22 +0000447
448.. _inspect-source:
449
450Retrieving source code
451----------------------
452
Georg Brandl116aa622007-08-15 14:28:22 +0000453.. function:: getdoc(object)
454
Georg Brandl0c77a822008-06-10 16:37:50 +0000455 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300456 If the documentation string for an object is not provided and the object is
457 a class, a method, a property or a descriptor, retrieve the documentation
458 string from the inheritance hierarchy.
Georg Brandl116aa622007-08-15 14:28:22 +0000459
Berker Peksag4333d8b2015-07-30 18:06:09 +0300460 .. versionchanged:: 3.5
461 Documentation strings are now inherited if not overridden.
462
Georg Brandl116aa622007-08-15 14:28:22 +0000463
464.. function:: getcomments(object)
465
466 Return in a single string any lines of comments immediately preceding the
467 object's source code (for a class, function, or method), or at the top of the
Marco Buttu3f2155f2017-03-17 09:50:23 +0100468 Python source file (if the object is a module). If the object's source code
469 is unavailable, return ``None``. This could happen if the object has been
470 defined in C or the interactive shell.
Georg Brandl116aa622007-08-15 14:28:22 +0000471
472
473.. function:: getfile(object)
474
475 Return the name of the (text or binary) file in which an object was defined.
476 This will fail with a :exc:`TypeError` if the object is a built-in module,
477 class, or function.
478
479
480.. function:: getmodule(object)
481
482 Try to guess which module an object was defined in.
483
484
485.. function:: getsourcefile(object)
486
487 Return the name of the Python source file in which an object was defined. This
488 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
489 function.
490
491
492.. function:: getsourcelines(object)
493
494 Return a list of source lines and starting line number for an object. The
495 argument may be a module, class, method, function, traceback, frame, or code
496 object. The source code is returned as a list of the lines corresponding to the
497 object and the line number indicates where in the original source file the first
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200498 line of code was found. An :exc:`OSError` is raised if the source code cannot
Georg Brandl116aa622007-08-15 14:28:22 +0000499 be retrieved.
500
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200501 .. versionchanged:: 3.3
502 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
503 former.
504
Georg Brandl116aa622007-08-15 14:28:22 +0000505
506.. function:: getsource(object)
507
508 Return the text of the source code for an object. The argument may be a module,
509 class, method, function, traceback, frame, or code object. The source code is
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200510 returned as a single string. An :exc:`OSError` is raised if the source code
Georg Brandl116aa622007-08-15 14:28:22 +0000511 cannot be retrieved.
512
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200513 .. versionchanged:: 3.3
514 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
515 former.
516
Georg Brandl116aa622007-08-15 14:28:22 +0000517
Georg Brandl0c77a822008-06-10 16:37:50 +0000518.. function:: cleandoc(doc)
519
520 Clean up indentation from docstrings that are indented to line up with blocks
Senthil Kumaranebd84e32016-05-29 20:36:58 -0700521 of code.
522
523 All leading whitespace is removed from the first line. Any leading whitespace
524 that can be uniformly removed from the second line onwards is removed. Empty
525 lines at the beginning and end are subsequently removed. Also, all tabs are
526 expanded to spaces.
Georg Brandl0c77a822008-06-10 16:37:50 +0000527
Georg Brandl0c77a822008-06-10 16:37:50 +0000528
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300529.. _inspect-signature-object:
530
Georg Brandle4717722012-08-14 09:45:28 +0200531Introspecting callables with the Signature object
532-------------------------------------------------
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300533
534.. versionadded:: 3.3
535
Georg Brandle4717722012-08-14 09:45:28 +0200536The Signature object represents the call signature of a callable object and its
537return annotation. To retrieve a Signature object, use the :func:`signature`
538function.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300539
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400540.. function:: signature(callable, \*, follow_wrapped=True)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300541
Georg Brandle4717722012-08-14 09:45:28 +0200542 Return a :class:`Signature` object for the given ``callable``::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300543
544 >>> from inspect import signature
545 >>> def foo(a, *, b:int, **kwargs):
546 ... pass
547
548 >>> sig = signature(foo)
549
550 >>> str(sig)
551 '(a, *, b:int, **kwargs)'
552
553 >>> str(sig.parameters['b'])
554 'b:int'
555
556 >>> sig.parameters['b'].annotation
557 <class 'int'>
558
Georg Brandle4717722012-08-14 09:45:28 +0200559 Accepts a wide range of python callables, from plain functions and classes to
560 :func:`functools.partial` objects.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300561
Larry Hastings5c661892014-01-24 06:17:25 -0800562 Raises :exc:`ValueError` if no signature can be provided, and
563 :exc:`TypeError` if that type of object is not supported.
564
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400565 .. versionadded:: 3.5
566 ``follow_wrapped`` parameter. Pass ``False`` to get a signature of
567 ``callable`` specifically (``callable.__wrapped__`` will not be used to
568 unwrap decorated callables.)
569
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300570 .. note::
571
Georg Brandle4717722012-08-14 09:45:28 +0200572 Some callables may not be introspectable in certain implementations of
Yury Selivanovd71e52f2014-01-30 00:22:57 -0500573 Python. For example, in CPython, some built-in functions defined in
574 C provide no metadata about their arguments.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300575
576
Yury Selivanov78356892014-01-30 00:10:54 -0500577.. class:: Signature(parameters=None, \*, return_annotation=Signature.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300578
Georg Brandle4717722012-08-14 09:45:28 +0200579 A Signature object represents the call signature of a function and its return
580 annotation. For each parameter accepted by the function it stores a
581 :class:`Parameter` object in its :attr:`parameters` collection.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300582
Yury Selivanov78356892014-01-30 00:10:54 -0500583 The optional *parameters* argument is a sequence of :class:`Parameter`
584 objects, which is validated to check that there are no parameters with
585 duplicate names, and that the parameters are in the right order, i.e.
586 positional-only first, then positional-or-keyword, and that parameters with
587 defaults follow parameters without defaults.
588
589 The optional *return_annotation* argument, can be an arbitrary Python object,
590 is the "return" annotation of the callable.
591
Georg Brandle4717722012-08-14 09:45:28 +0200592 Signature objects are *immutable*. Use :meth:`Signature.replace` to make a
593 modified copy.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300594
Yury Selivanov67d727e2014-03-29 13:24:14 -0400595 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400596 Signature objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400597
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300598 .. attribute:: Signature.empty
599
600 A special class-level marker to specify absence of a return annotation.
601
602 .. attribute:: Signature.parameters
603
604 An ordered mapping of parameters' names to the corresponding
605 :class:`Parameter` objects.
606
607 .. attribute:: Signature.return_annotation
608
Georg Brandle4717722012-08-14 09:45:28 +0200609 The "return" annotation for the callable. If the callable has no "return"
610 annotation, this attribute is set to :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300611
612 .. method:: Signature.bind(*args, **kwargs)
613
Georg Brandle4717722012-08-14 09:45:28 +0200614 Create a mapping from positional and keyword arguments to parameters.
615 Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
616 signature, or raises a :exc:`TypeError`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300617
618 .. method:: Signature.bind_partial(*args, **kwargs)
619
Georg Brandle4717722012-08-14 09:45:28 +0200620 Works the same way as :meth:`Signature.bind`, but allows the omission of
621 some required arguments (mimics :func:`functools.partial` behavior.)
622 Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
623 passed arguments do not match the signature.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300624
Ezio Melotti8429b672012-09-14 06:35:09 +0300625 .. method:: Signature.replace(*[, parameters][, return_annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300626
Georg Brandle4717722012-08-14 09:45:28 +0200627 Create a new Signature instance based on the instance replace was invoked
628 on. It is possible to pass different ``parameters`` and/or
629 ``return_annotation`` to override the corresponding properties of the base
630 signature. To remove return_annotation from the copied Signature, pass in
631 :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300632
633 ::
634
635 >>> def test(a, b):
636 ... pass
637 >>> sig = signature(test)
638 >>> new_sig = sig.replace(return_annotation="new return anno")
639 >>> str(new_sig)
640 "(a, b) -> 'new return anno'"
641
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400642 .. classmethod:: Signature.from_callable(obj, \*, follow_wrapped=True)
Yury Selivanovda396452014-03-27 12:09:24 -0400643
644 Return a :class:`Signature` (or its subclass) object for a given callable
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400645 ``obj``. Pass ``follow_wrapped=False`` to get a signature of ``obj``
646 without unwrapping its ``__wrapped__`` chain.
Yury Selivanovda396452014-03-27 12:09:24 -0400647
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400648 This method simplifies subclassing of :class:`Signature`::
Yury Selivanovda396452014-03-27 12:09:24 -0400649
650 class MySignature(Signature):
651 pass
652 sig = MySignature.from_callable(min)
653 assert isinstance(sig, MySignature)
654
Yury Selivanov232b9342014-03-29 13:18:30 -0400655 .. versionadded:: 3.5
656
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300657
Yury Selivanov78356892014-01-30 00:10:54 -0500658.. class:: Parameter(name, kind, \*, default=Parameter.empty, annotation=Parameter.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300659
Georg Brandle4717722012-08-14 09:45:28 +0200660 Parameter objects are *immutable*. Instead of modifying a Parameter object,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300661 you can use :meth:`Parameter.replace` to create a modified copy.
662
Yury Selivanov67d727e2014-03-29 13:24:14 -0400663 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400664 Parameter objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400665
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300666 .. attribute:: Parameter.empty
667
Georg Brandle4717722012-08-14 09:45:28 +0200668 A special class-level marker to specify absence of default values and
669 annotations.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300670
671 .. attribute:: Parameter.name
672
Yury Selivanov2393dca2014-01-27 15:07:58 -0500673 The name of the parameter as a string. The name must be a valid
674 Python identifier.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300675
Nick Coghlanb4b966e2016-06-04 14:40:03 -0700676 .. impl-detail::
677
678 CPython generates implicit parameter names of the form ``.0`` on the
679 code objects used to implement comprehensions and generator
680 expressions.
681
682 .. versionchanged:: 3.6
683 These parameter names are exposed by this module as names like
684 ``implicit0``.
685
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300686 .. attribute:: Parameter.default
687
Georg Brandle4717722012-08-14 09:45:28 +0200688 The default value for the parameter. If the parameter has no default
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300689 value, this attribute is set to :attr:`Parameter.empty`.
690
691 .. attribute:: Parameter.annotation
692
Georg Brandle4717722012-08-14 09:45:28 +0200693 The annotation for the parameter. If the parameter has no annotation,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300694 this attribute is set to :attr:`Parameter.empty`.
695
696 .. attribute:: Parameter.kind
697
Georg Brandle4717722012-08-14 09:45:28 +0200698 Describes how argument values are bound to the parameter. Possible values
699 (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300700
Georg Brandl44ea77b2013-03-28 13:28:44 +0100701 .. tabularcolumns:: |l|L|
702
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300703 +------------------------+----------------------------------------------+
704 | Name | Meaning |
705 +========================+==============================================+
706 | *POSITIONAL_ONLY* | Value must be supplied as a positional |
707 | | argument. |
708 | | |
709 | | Python has no explicit syntax for defining |
710 | | positional-only parameters, but many built-in|
711 | | and extension module functions (especially |
712 | | those that accept only one or two parameters)|
713 | | accept them. |
714 +------------------------+----------------------------------------------+
715 | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
716 | | positional argument (this is the standard |
717 | | binding behaviour for functions implemented |
718 | | in Python.) |
719 +------------------------+----------------------------------------------+
720 | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
721 | | bound to any other parameter. This |
722 | | corresponds to a ``*args`` parameter in a |
723 | | Python function definition. |
724 +------------------------+----------------------------------------------+
725 | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
726 | | Keyword only parameters are those which |
727 | | appear after a ``*`` or ``*args`` entry in a |
728 | | Python function definition. |
729 +------------------------+----------------------------------------------+
730 | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
731 | | to any other parameter. This corresponds to a|
732 | | ``**kwargs`` parameter in a Python function |
733 | | definition. |
734 +------------------------+----------------------------------------------+
735
Andrew Svetloveed18082012-08-13 18:23:54 +0300736 Example: print all keyword-only arguments without default values::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300737
738 >>> def foo(a, b, *, c, d=10):
739 ... pass
740
741 >>> sig = signature(foo)
742 >>> for param in sig.parameters.values():
743 ... if (param.kind == param.KEYWORD_ONLY and
744 ... param.default is param.empty):
745 ... print('Parameter:', param)
746 Parameter: c
747
Ezio Melotti8429b672012-09-14 06:35:09 +0300748 .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300749
Georg Brandle4717722012-08-14 09:45:28 +0200750 Create a new Parameter instance based on the instance replaced was invoked
751 on. To override a :class:`Parameter` attribute, pass the corresponding
752 argument. To remove a default value or/and an annotation from a
753 Parameter, pass :attr:`Parameter.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300754
755 ::
756
757 >>> from inspect import Parameter
758 >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
759 >>> str(param)
760 'foo=42'
761
762 >>> str(param.replace()) # Will create a shallow copy of 'param'
763 'foo=42'
764
765 >>> str(param.replace(default=Parameter.empty, annotation='spam'))
766 "foo:'spam'"
767
Yury Selivanov2393dca2014-01-27 15:07:58 -0500768 .. versionchanged:: 3.4
769 In Python 3.3 Parameter objects were allowed to have ``name`` set
770 to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``.
771 This is no longer permitted.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300772
773.. class:: BoundArguments
774
775 Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
776 Holds the mapping of arguments to the function's parameters.
777
778 .. attribute:: BoundArguments.arguments
779
780 An ordered, mutable mapping (:class:`collections.OrderedDict`) of
Georg Brandle4717722012-08-14 09:45:28 +0200781 parameters' names to arguments' values. Contains only explicitly bound
782 arguments. Changes in :attr:`arguments` will reflect in :attr:`args` and
783 :attr:`kwargs`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300784
Georg Brandle4717722012-08-14 09:45:28 +0200785 Should be used in conjunction with :attr:`Signature.parameters` for any
786 argument processing purposes.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300787
788 .. note::
789
790 Arguments for which :meth:`Signature.bind` or
791 :meth:`Signature.bind_partial` relied on a default value are skipped.
Yury Selivanovb907a512015-05-16 13:45:09 -0400792 However, if needed, use :meth:`BoundArguments.apply_defaults` to add
793 them.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300794
795 .. attribute:: BoundArguments.args
796
Georg Brandle4717722012-08-14 09:45:28 +0200797 A tuple of positional arguments values. Dynamically computed from the
798 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300799
800 .. attribute:: BoundArguments.kwargs
801
Georg Brandle4717722012-08-14 09:45:28 +0200802 A dict of keyword arguments values. Dynamically computed from the
803 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300804
Yury Selivanov82796192015-05-14 14:14:02 -0400805 .. attribute:: BoundArguments.signature
806
807 A reference to the parent :class:`Signature` object.
808
Yury Selivanovb907a512015-05-16 13:45:09 -0400809 .. method:: BoundArguments.apply_defaults()
810
811 Set default values for missing arguments.
812
813 For variable-positional arguments (``*args``) the default is an
814 empty tuple.
815
816 For variable-keyword arguments (``**kwargs``) the default is an
817 empty dict.
818
819 ::
820
821 >>> def foo(a, b='ham', *args): pass
822 >>> ba = inspect.signature(foo).bind('spam')
823 >>> ba.apply_defaults()
824 >>> ba.arguments
825 OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])
826
Berker Peksag5b3df5b2015-05-16 23:29:31 +0300827 .. versionadded:: 3.5
828
Georg Brandle4717722012-08-14 09:45:28 +0200829 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
830 functions::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300831
832 def test(a, *, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300833 ...
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300834
835 sig = signature(test)
836 ba = sig.bind(10, b=20)
837 test(*ba.args, **ba.kwargs)
838
839
Georg Brandle4717722012-08-14 09:45:28 +0200840.. seealso::
841
842 :pep:`362` - Function Signature Object.
843 The detailed specification, implementation details and examples.
844
845
Georg Brandl116aa622007-08-15 14:28:22 +0000846.. _inspect-classes-functions:
847
848Classes and functions
849---------------------
850
Georg Brandl3dd33882009-06-01 17:35:27 +0000851.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000852
853 Arrange the given list of classes into a hierarchy of nested lists. Where a
854 nested list appears, it contains classes derived from the class whose entry
855 immediately precedes the list. Each entry is a 2-tuple containing a class and a
856 tuple of its base classes. If the *unique* argument is true, exactly one entry
857 appears in the returned structure for each class in the given list. Otherwise,
858 classes using multiple inheritance and their descendants will appear multiple
859 times.
860
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500861
862.. function:: getargspec(func)
863
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000864 Get the names and default values of a Python function's parameters. A
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500865 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000866 returned. *args* is a list of the parameter names. *varargs* and *keywords*
867 are the names of the ``*`` and ``**`` parameters or ``None``. *defaults* is a
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500868 tuple of default argument values or ``None`` if there are no default
869 arguments; if this tuple has *n* elements, they correspond to the last
870 *n* elements listed in *args*.
871
872 .. deprecated:: 3.0
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000873 Use :func:`getfullargspec` for an updated API that is usually a drop-in
874 replacement, but also correctly handles function annotations and
875 keyword-only parameters.
876
877 Alternatively, use :func:`signature` and
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500878 :ref:`Signature Object <inspect-signature-object>`, which provide a
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000879 more structured introspection API for callables.
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500880
881
Georg Brandl138bcb52007-09-12 19:04:21 +0000882.. function:: getfullargspec(func)
883
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000884 Get the names and default values of a Python function's parameters. A
Georg Brandl82402752010-01-09 09:48:46 +0000885 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000886
Georg Brandl3dd33882009-06-01 17:35:27 +0000887 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
888 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000889
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000890 *args* is a list of the positional parameter names.
891 *varargs* is the name of the ``*`` parameter or ``None`` if arbitrary
892 positional arguments are not accepted.
893 *varkw* is the name of the ``**`` parameter or ``None`` if arbitrary
894 keyword arguments are not accepted.
895 *defaults* is an *n*-tuple of default argument values corresponding to the
896 last *n* positional parameters, or ``None`` if there are no such defaults
897 defined.
898 *kwonlyargs* is a list of keyword-only parameter names.
899 *kwonlydefaults* is a dictionary mapping parameter names from *kwonlyargs*
900 to the default values used if no argument is supplied.
901 *annotations* is a dictionary mapping parameter names to annotations.
902 The special key ``"return"`` is used to report the function return value
903 annotation (if any).
904
905 Note that :func:`signature` and
906 :ref:`Signature Object <inspect-signature-object>` provide the recommended
907 API for callable introspection, and support additional behaviours (like
908 positional-only arguments) that are sometimes encountered in extension module
909 APIs. This function is retained primarily for use in code that needs to
910 maintain compatibility with the Python 2 ``inspect`` module API.
Georg Brandl138bcb52007-09-12 19:04:21 +0000911
Nick Coghlan16355782014-03-08 16:36:37 +1000912 .. versionchanged:: 3.4
913 This function is now based on :func:`signature`, but still ignores
914 ``__wrapped__`` attributes and includes the already bound first
915 parameter in the signature output for bound methods.
916
Nick Coghlan3c35fdb2016-12-02 20:29:57 +1000917 .. versionchanged:: 3.6
918 This method was previously documented as deprecated in favour of
919 :func:`signature` in Python 3.5, but that decision has been reversed
920 in order to restore a clearly supported standard interface for
921 single-source Python 2/3 code migrating away from the legacy
922 :func:`getargspec` API.
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400923
Georg Brandl116aa622007-08-15 14:28:22 +0000924
925.. function:: getargvalues(frame)
926
Georg Brandl3dd33882009-06-01 17:35:27 +0000927 Get information about arguments passed into a particular frame. A
928 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000929 returned. *args* is a list of the argument names. *varargs* and *keywords*
930 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000931 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000932
Matthias Bussonnier0899b982017-02-21 21:45:51 -0800933 .. note::
934 This function was inadvertently marked as deprecated in Python 3.5.
Yury Selivanov945fff42015-05-22 16:28:05 -0400935
Georg Brandl116aa622007-08-15 14:28:22 +0000936
Andrew Svetlov735d3172012-10-27 00:28:20 +0300937.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Georg Brandl116aa622007-08-15 14:28:22 +0000938
Michael Foord3af125a2012-04-21 18:22:28 +0100939 Format a pretty argument spec from the values returned by
Berker Peksagfa3922c2015-07-31 04:11:29 +0300940 :func:`getfullargspec`.
Michael Foord3af125a2012-04-21 18:22:28 +0100941
942 The first seven arguments are (``args``, ``varargs``, ``varkw``,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100943 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
Andrew Svetlov735d3172012-10-27 00:28:20 +0300944
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100945 The other six arguments are functions that are called to turn argument names,
946 ``*`` argument name, ``**`` argument name, default values, return annotation
947 and individual annotations into strings, respectively.
948
949 For example:
950
951 >>> from inspect import formatargspec, getfullargspec
952 >>> def f(a: int, b: float):
953 ... pass
954 ...
955 >>> formatargspec(*getfullargspec(f))
956 '(a: int, b: float)'
Georg Brandl116aa622007-08-15 14:28:22 +0000957
Yury Selivanov945fff42015-05-22 16:28:05 -0400958 .. deprecated:: 3.5
959 Use :func:`signature` and
960 :ref:`Signature Object <inspect-signature-object>`, which provide a
961 better introspecting API for callables.
962
Georg Brandl116aa622007-08-15 14:28:22 +0000963
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000964.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000965
966 Format a pretty argument spec from the four values returned by
967 :func:`getargvalues`. The format\* arguments are the corresponding optional
968 formatting functions that are called to turn names and values into strings.
969
Matthias Bussonnier0899b982017-02-21 21:45:51 -0800970 .. note::
971 This function was inadvertently marked as deprecated in Python 3.5.
Yury Selivanov945fff42015-05-22 16:28:05 -0400972
Georg Brandl116aa622007-08-15 14:28:22 +0000973
974.. function:: getmro(cls)
975
976 Return a tuple of class cls's base classes, including cls, in method resolution
977 order. No class appears more than once in this tuple. Note that the method
978 resolution order depends on cls's type. Unless a very peculiar user-defined
979 metatype is in use, cls will be the first element of the tuple.
980
981
Benjamin Peterson3a990c62014-01-02 12:22:30 -0600982.. function:: getcallargs(func, *args, **kwds)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000983
984 Bind the *args* and *kwds* to the argument names of the Python function or
985 method *func*, as if it was called with them. For bound methods, bind also the
986 first argument (typically named ``self``) to the associated instance. A dict
987 is returned, mapping the argument names (including the names of the ``*`` and
988 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
989 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
990 an exception because of incompatible signature, an exception of the same type
991 and the same or similar message is raised. For example::
992
993 >>> from inspect import getcallargs
994 >>> def f(a, b=1, *pos, **named):
995 ... pass
Andrew Svetlove939f382012-08-09 13:25:32 +0300996 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
997 True
998 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
999 True
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001000 >>> getcallargs(f)
1001 Traceback (most recent call last):
1002 ...
Andrew Svetlove939f382012-08-09 13:25:32 +03001003 TypeError: f() missing 1 required positional argument: 'a'
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001004
1005 .. versionadded:: 3.2
1006
Yury Selivanov3cfec2e2015-05-22 11:38:38 -04001007 .. deprecated:: 3.5
1008 Use :meth:`Signature.bind` and :meth:`Signature.bind_partial` instead.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +03001009
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +00001010
Nick Coghlan2f92e542012-06-23 19:39:55 +10001011.. function:: getclosurevars(func)
1012
1013 Get the mapping of external name references in a Python function or
1014 method *func* to their current values. A
1015 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
1016 is returned. *nonlocals* maps referenced names to lexical closure
1017 variables, *globals* to the function's module globals and *builtins* to
1018 the builtins visible from the function body. *unbound* is the set of names
1019 referenced in the function that could not be resolved at all given the
1020 current module globals and builtins.
1021
1022 :exc:`TypeError` is raised if *func* is not a Python function or method.
1023
1024 .. versionadded:: 3.3
1025
1026
Nick Coghlane8c45d62013-07-28 20:00:01 +10001027.. function:: unwrap(func, *, stop=None)
1028
1029 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
1030 attributes returning the last object in the chain.
1031
1032 *stop* is an optional callback accepting an object in the wrapper chain
1033 as its sole argument that allows the unwrapping to be terminated early if
1034 the callback returns a true value. If the callback never returns a true
1035 value, the last object in the chain is returned as usual. For example,
1036 :func:`signature` uses this to stop unwrapping if any object in the
1037 chain has a ``__signature__`` attribute defined.
1038
1039 :exc:`ValueError` is raised if a cycle is encountered.
1040
1041 .. versionadded:: 3.4
1042
1043
Georg Brandl116aa622007-08-15 14:28:22 +00001044.. _inspect-stack:
1045
1046The interpreter stack
1047---------------------
1048
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001049When the following functions return "frame records," each record is a
1050:term:`named tuple`
1051``FrameInfo(frame, filename, lineno, function, code_context, index)``.
1052The tuple contains the frame object, the filename, the line number of the
1053current line,
Georg Brandl116aa622007-08-15 14:28:22 +00001054the function name, a list of lines of context from the source code, and the
1055index of the current line within that list.
1056
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001057.. versionchanged:: 3.5
1058 Return a named tuple instead of a tuple.
1059
Georg Brandle720c0a2009-04-27 16:20:50 +00001060.. note::
Georg Brandl116aa622007-08-15 14:28:22 +00001061
1062 Keeping references to frame objects, as found in the first element of the frame
1063 records these functions return, can cause your program to create reference
1064 cycles. Once a reference cycle has been created, the lifespan of all objects
1065 which can be accessed from the objects which form the cycle can become much
1066 longer even if Python's optional cycle detector is enabled. If such cycles must
1067 be created, it is important to ensure they are explicitly broken to avoid the
1068 delayed destruction of objects and increased memory consumption which occurs.
1069
1070 Though the cycle detector will catch these, destruction of the frames (and local
1071 variables) can be made deterministic by removing the cycle in a
1072 :keyword:`finally` clause. This is also important if the cycle detector was
1073 disabled when Python was compiled or using :func:`gc.disable`. For example::
1074
1075 def handle_stackframe_without_leak():
1076 frame = inspect.currentframe()
1077 try:
1078 # do something with the frame
1079 finally:
1080 del frame
1081
Antoine Pitrou58720d62013-08-05 23:26:40 +02001082 If you want to keep the frame around (for example to print a traceback
1083 later), you can also break reference cycles by using the
1084 :meth:`frame.clear` method.
1085
Georg Brandl116aa622007-08-15 14:28:22 +00001086The optional *context* argument supported by most of these functions specifies
1087the number of lines of context to return, which are centered around the current
1088line.
1089
1090
Georg Brandl3dd33882009-06-01 17:35:27 +00001091.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001092
Georg Brandl48310cd2009-01-03 21:18:54 +00001093 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +00001094 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +00001095
1096
Georg Brandl3dd33882009-06-01 17:35:27 +00001097.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001098
1099 Get a list of frame records for a frame and all outer frames. These frames
1100 represent the calls that lead to the creation of *frame*. The first entry in the
1101 returned list represents *frame*; the last entry represents the outermost call
1102 on *frame*'s stack.
1103
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001104 .. versionchanged:: 3.5
1105 A list of :term:`named tuples <named tuple>`
1106 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1107 is returned.
1108
Georg Brandl116aa622007-08-15 14:28:22 +00001109
Georg Brandl3dd33882009-06-01 17:35:27 +00001110.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001111
1112 Get a list of frame records for a traceback's frame and all inner frames. These
1113 frames represent calls made as a consequence of *frame*. The first entry in the
1114 list represents *traceback*; the last entry represents where the exception was
1115 raised.
1116
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001117 .. versionchanged:: 3.5
1118 A list of :term:`named tuples <named tuple>`
1119 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1120 is returned.
1121
Georg Brandl116aa622007-08-15 14:28:22 +00001122
1123.. function:: currentframe()
1124
1125 Return the frame object for the caller's stack frame.
1126
Georg Brandl495f7b52009-10-27 15:28:25 +00001127 .. impl-detail::
1128
1129 This function relies on Python stack frame support in the interpreter,
1130 which isn't guaranteed to exist in all implementations of Python. If
1131 running in an implementation without Python stack frame support this
1132 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001133
Georg Brandl116aa622007-08-15 14:28:22 +00001134
Georg Brandl3dd33882009-06-01 17:35:27 +00001135.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001136
1137 Return a list of frame records for the caller's stack. The first entry in the
1138 returned list represents the caller; the last entry represents the outermost
1139 call on the stack.
1140
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001141 .. versionchanged:: 3.5
1142 A list of :term:`named tuples <named tuple>`
1143 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1144 is returned.
1145
Georg Brandl116aa622007-08-15 14:28:22 +00001146
Georg Brandl3dd33882009-06-01 17:35:27 +00001147.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001148
1149 Return a list of frame records for the stack between the current frame and the
1150 frame in which an exception currently being handled was raised in. The first
1151 entry in the list represents the caller; the last entry represents where the
1152 exception was raised.
1153
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001154 .. versionchanged:: 3.5
1155 A list of :term:`named tuples <named tuple>`
1156 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1157 is returned.
1158
Michael Foord95fc51d2010-11-20 15:07:30 +00001159
1160Fetching attributes statically
1161------------------------------
1162
1163Both :func:`getattr` and :func:`hasattr` can trigger code execution when
1164fetching or checking for the existence of attributes. Descriptors, like
1165properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
1166may be called.
1167
1168For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +02001169can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +00001170but avoids executing code when it fetches attributes.
1171
1172.. function:: getattr_static(obj, attr, default=None)
1173
1174 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +02001175 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +00001176
1177 Note: this function may not be able to retrieve all attributes
1178 that getattr can fetch (like dynamically created attributes)
1179 and may find attributes that getattr can't (like descriptors
1180 that raise AttributeError). It can also return descriptors objects
1181 instead of instance members.
1182
Serhiy Storchakabfdcd432013-10-13 23:09:14 +03001183 If the instance :attr:`~object.__dict__` is shadowed by another member (for
1184 example a property) then this function will be unable to find instance
1185 members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001186
Michael Foorddcebe0f2011-03-15 19:20:44 -04001187 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +00001188
Éric Araujo941afed2011-09-01 02:47:34 +02001189:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +00001190getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +00001191is returned instead of the underlying attribute.
1192
1193You can handle these with code like the following. Note that
1194for arbitrary getset descriptors invoking these may trigger
1195code execution::
1196
1197 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +00001198 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +00001199 __slots__ = ['foo']
1200
1201 slot_descriptor = type(_foo.foo)
1202 getset_descriptor = type(type(open(__file__)).name)
1203 wrapper_descriptor = type(str.__dict__['__add__'])
1204 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
1205
1206 result = getattr_static(some_object, 'foo')
1207 if type(result) in descriptor_types:
1208 try:
1209 result = result.__get__()
1210 except AttributeError:
1211 # descriptors can raise AttributeError to
1212 # indicate there is no underlying value
1213 # in which case the descriptor itself will
1214 # have to do
1215 pass
Nick Coghlane0f04652010-11-21 03:44:04 +00001216
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001217
Yury Selivanov5376ba92015-06-22 12:19:30 -04001218Current State of Generators and Coroutines
1219------------------------------------------
Nick Coghlane0f04652010-11-21 03:44:04 +00001220
1221When implementing coroutine schedulers and for other advanced uses of
1222generators, it is useful to determine whether a generator is currently
1223executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001224terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +00001225generator to be determined easily.
1226
1227.. function:: getgeneratorstate(generator)
1228
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001229 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +00001230
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001231 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +00001232 * GEN_CREATED: Waiting to start execution.
1233 * GEN_RUNNING: Currently being executed by the interpreter.
1234 * GEN_SUSPENDED: Currently suspended at a yield expression.
1235 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +00001236
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001237 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001238
Yury Selivanov5376ba92015-06-22 12:19:30 -04001239.. function:: getcoroutinestate(coroutine)
1240
1241 Get current state of a coroutine object. The function is intended to be
1242 used with coroutine objects created by :keyword:`async def` functions, but
1243 will accept any coroutine-like object that has ``cr_running`` and
1244 ``cr_frame`` attributes.
1245
1246 Possible states are:
1247 * CORO_CREATED: Waiting to start execution.
1248 * CORO_RUNNING: Currently being executed by the interpreter.
1249 * CORO_SUSPENDED: Currently suspended at an await expression.
1250 * CORO_CLOSED: Execution has completed.
1251
1252 .. versionadded:: 3.5
1253
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001254The current internal state of the generator can also be queried. This is
1255mostly useful for testing purposes, to ensure that internal state is being
1256updated as expected:
1257
1258.. function:: getgeneratorlocals(generator)
1259
1260 Get the mapping of live local variables in *generator* to their current
1261 values. A dictionary is returned that maps from variable names to values.
1262 This is the equivalent of calling :func:`locals` in the body of the
1263 generator, and all the same caveats apply.
1264
1265 If *generator* is a :term:`generator` with no currently associated frame,
1266 then an empty dictionary is returned. :exc:`TypeError` is raised if
1267 *generator* is not a Python generator object.
1268
1269 .. impl-detail::
1270
1271 This function relies on the generator exposing a Python stack frame
1272 for introspection, which isn't guaranteed to be the case in all
1273 implementations of Python. In such cases, this function will always
1274 return an empty dictionary.
1275
1276 .. versionadded:: 3.3
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001277
Yury Selivanov5376ba92015-06-22 12:19:30 -04001278.. function:: getcoroutinelocals(coroutine)
1279
1280 This function is analogous to :func:`~inspect.getgeneratorlocals`, but
1281 works for coroutine objects created by :keyword:`async def` functions.
1282
1283 .. versionadded:: 3.5
1284
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001285
Yury Selivanovea75a512016-10-20 13:06:30 -04001286.. _inspect-module-co-flags:
1287
1288Code Objects Bit Flags
1289----------------------
1290
1291Python code objects have a ``co_flags`` attribute, which is a bitmap of
1292the following flags:
1293
Xiang Zhanga6902e62017-04-13 10:38:28 +08001294.. data:: CO_OPTIMIZED
1295
1296 The code object is optimized, using fast locals.
1297
Yury Selivanovea75a512016-10-20 13:06:30 -04001298.. data:: CO_NEWLOCALS
1299
1300 If set, a new dict will be created for the frame's ``f_locals`` when
1301 the code object is executed.
1302
1303.. data:: CO_VARARGS
1304
1305 The code object has a variable positional parameter (``*args``-like).
1306
1307.. data:: CO_VARKEYWORDS
1308
1309 The code object has a variable keyword parameter (``**kwargs``-like).
1310
Xiang Zhanga6902e62017-04-13 10:38:28 +08001311.. data:: CO_NESTED
1312
1313 The flag is set when the code object is a nested function.
1314
Yury Selivanovea75a512016-10-20 13:06:30 -04001315.. data:: CO_GENERATOR
1316
1317 The flag is set when the code object is a generator function, i.e.
1318 a generator object is returned when the code object is executed.
1319
1320.. data:: CO_NOFREE
1321
1322 The flag is set if there are no free or cell variables.
1323
1324.. data:: CO_COROUTINE
1325
Yury Selivanovb738a1f2016-10-20 16:30:51 -04001326 The flag is set when the code object is a coroutine function.
1327 When the code object is executed it returns a coroutine object.
1328 See :pep:`492` for more details.
Yury Selivanovea75a512016-10-20 13:06:30 -04001329
1330 .. versionadded:: 3.5
1331
1332.. data:: CO_ITERABLE_COROUTINE
1333
Yury Selivanovb738a1f2016-10-20 16:30:51 -04001334 The flag is used to transform generators into generator-based
1335 coroutines. Generator objects with this flag can be used in
1336 ``await`` expression, and can ``yield from`` coroutine objects.
1337 See :pep:`492` for more details.
Yury Selivanovea75a512016-10-20 13:06:30 -04001338
1339 .. versionadded:: 3.5
1340
Yury Selivanove20fed92016-10-20 13:11:34 -04001341.. data:: CO_ASYNC_GENERATOR
1342
Yury Selivanovb738a1f2016-10-20 16:30:51 -04001343 The flag is set when the code object is an asynchronous generator
1344 function. When the code object is executed it returns an
1345 asynchronous generator object. See :pep:`525` for more details.
Yury Selivanove20fed92016-10-20 13:11:34 -04001346
1347 .. versionadded:: 3.6
1348
Yury Selivanovea75a512016-10-20 13:06:30 -04001349.. note::
1350 The flags are specific to CPython, and may not be defined in other
1351 Python implementations. Furthermore, the flags are an implementation
1352 detail, and can be removed or deprecated in future Python releases.
1353 It's recommended to use public APIs from the :mod:`inspect` module
1354 for any introspection needs.
1355
1356
Nick Coghlan367df122013-10-27 01:57:34 +10001357.. _inspect-module-cli:
1358
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001359Command Line Interface
1360----------------------
1361
1362The :mod:`inspect` module also provides a basic introspection capability
1363from the command line.
1364
1365.. program:: inspect
1366
1367By default, accepts the name of a module and prints the source of that
1368module. A class or function within the module can be printed instead by
1369appended a colon and the qualified name of the target object.
1370
1371.. cmdoption:: --details
1372
1373 Print information about the specified object rather than the source code