blob: 8e7ed19f296a694143e1cdce74ce5934b6b29d57 [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
Georg Brandl55ac8f02007-09-01 13:51:09 +000037+-----------+-----------------+---------------------------+
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+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -040047| | __name__ | name with which this |
48| | | class was defined |
49+-----------+-----------------+---------------------------+
50| | __qualname__ | qualified name |
51+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +000052| | __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+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -040060| | __qualname__ | qualified name |
61+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000062| | __func__ | function object |
Georg Brandl55ac8f02007-09-01 13:51:09 +000063| | | containing implementation |
64| | | of method |
65+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000066| | __self__ | instance to which this |
Georg Brandl55ac8f02007-09-01 13:51:09 +000067| | | method is bound, or |
68| | | ``None`` |
69+-----------+-----------------+---------------------------+
70| function | __doc__ | documentation string |
71+-----------+-----------------+---------------------------+
72| | __name__ | name with which this |
73| | | function was defined |
74+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -040075| | __qualname__ | qualified name |
76+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +000077| | __code__ | code object containing |
78| | | compiled function |
Georg Brandl9afde1c2007-11-01 20:32:30 +000079| | | :term:`bytecode` |
Georg Brandl55ac8f02007-09-01 13:51:09 +000080+-----------+-----------------+---------------------------+
81| | __defaults__ | tuple of any default |
Yury Selivanovea2d66e2014-01-27 14:26:28 -050082| | | values for positional or |
83| | | keyword parameters |
84+-----------+-----------------+---------------------------+
85| | __kwdefaults__ | mapping of any default |
86| | | values for keyword-only |
87| | | parameters |
Georg Brandl55ac8f02007-09-01 13:51:09 +000088+-----------+-----------------+---------------------------+
89| | __globals__ | global namespace in which |
90| | | this function was defined |
91+-----------+-----------------+---------------------------+
Yury Selivanovc62162d2015-10-31 13:29:15 -040092| | __annotations__ | mapping of parameters |
93| | | names to annotations; |
94| | | ``"return"`` key is |
95| | | reserved for return |
96| | | annotations. |
97+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +000098| 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+-----------+-----------------+---------------------------+
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000114| | f_builtins | builtins namespace seen |
Georg Brandl55ac8f02007-09-01 13:51:09 +0000115| | | by this frame |
116+-----------+-----------------+---------------------------+
117| | f_code | code object being |
118| | | executed in this frame |
119+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000120| | f_globals | global namespace seen by |
121| | | this frame |
122+-----------+-----------------+---------------------------+
123| | f_lasti | index of last attempted |
124| | | instruction in bytecode |
125+-----------+-----------------+---------------------------+
126| | f_lineno | current line number in |
127| | | Python source code |
128+-----------+-----------------+---------------------------+
129| | f_locals | local namespace seen by |
130| | | this frame |
131+-----------+-----------------+---------------------------+
132| | f_restricted | 0 or 1 if frame is in |
133| | | restricted execution mode |
134+-----------+-----------------+---------------------------+
135| | f_trace | tracing function for this |
136| | | frame, or ``None`` |
137+-----------+-----------------+---------------------------+
138| code | co_argcount | number of arguments (not |
139| | | including \* or \*\* |
140| | | args) |
141+-----------+-----------------+---------------------------+
142| | co_code | string of raw compiled |
143| | | bytecode |
144+-----------+-----------------+---------------------------+
145| | co_consts | tuple of constants used |
146| | | in the bytecode |
147+-----------+-----------------+---------------------------+
148| | co_filename | name of file in which |
149| | | this code object was |
150| | | created |
151+-----------+-----------------+---------------------------+
152| | co_firstlineno | number of first line in |
153| | | Python source code |
154+-----------+-----------------+---------------------------+
155| | co_flags | bitmap: 1=optimized ``|`` |
156| | | 2=newlocals ``|`` 4=\*arg |
157| | | ``|`` 8=\*\*arg |
158+-----------+-----------------+---------------------------+
159| | co_lnotab | encoded mapping of line |
160| | | numbers to bytecode |
161| | | indices |
162+-----------+-----------------+---------------------------+
163| | co_name | name with which this code |
164| | | object was defined |
165+-----------+-----------------+---------------------------+
166| | co_names | tuple of names of local |
167| | | variables |
168+-----------+-----------------+---------------------------+
169| | co_nlocals | number of local variables |
170+-----------+-----------------+---------------------------+
171| | co_stacksize | virtual machine stack |
172| | | space required |
173+-----------+-----------------+---------------------------+
174| | co_varnames | tuple of names of |
175| | | arguments and local |
176| | | variables |
177+-----------+-----------------+---------------------------+
Victor Stinner40ee3012014-06-16 15:59:28 +0200178| generator | __name__ | name |
179+-----------+-----------------+---------------------------+
180| | __qualname__ | qualified name |
181+-----------+-----------------+---------------------------+
182| | gi_frame | frame |
183+-----------+-----------------+---------------------------+
184| | gi_running | is the generator running? |
185+-----------+-----------------+---------------------------+
186| | gi_code | code |
187+-----------+-----------------+---------------------------+
Yury Selivanovc135f0a2015-08-17 13:02:42 -0400188| | gi_yieldfrom | object being iterated by |
189| | | ``yield from``, or |
190| | | ``None`` |
191+-----------+-----------------+---------------------------+
Yury Selivanov5376ba92015-06-22 12:19:30 -0400192| coroutine | __name__ | name |
193+-----------+-----------------+---------------------------+
194| | __qualname__ | qualified name |
195+-----------+-----------------+---------------------------+
Yury Selivanove13f8f32015-07-03 00:23:30 -0400196| | cr_await | object being awaited on, |
197| | | or ``None`` |
198+-----------+-----------------+---------------------------+
Yury Selivanov5376ba92015-06-22 12:19:30 -0400199| | cr_frame | frame |
200+-----------+-----------------+---------------------------+
201| | cr_running | is the coroutine running? |
202+-----------+-----------------+---------------------------+
203| | cr_code | code |
204+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000205| builtin | __doc__ | documentation string |
206+-----------+-----------------+---------------------------+
207| | __name__ | original name of this |
208| | | function or method |
209+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -0400210| | __qualname__ | qualified name |
211+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000212| | __self__ | instance to which a |
213| | | method is bound, or |
214| | | ``None`` |
215+-----------+-----------------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000216
Victor Stinner40ee3012014-06-16 15:59:28 +0200217.. versionchanged:: 3.5
218
Yury Selivanov5fbad3c2015-08-17 13:04:41 -0400219 Add ``__qualname__`` and ``gi_yieldfrom`` attributes to generators.
220
221 The ``__name__`` attribute of generators is now set from the function
222 name, instead of the code name, and it can now be modified.
Victor Stinner40ee3012014-06-16 15:59:28 +0200223
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225.. function:: getmembers(object[, predicate])
226
227 Return all the members of an object in a list of (name, value) pairs sorted by
228 name. If the optional *predicate* argument is supplied, only members for which
229 the predicate returns a true value are included.
230
Christian Heimes7f044312008-01-06 17:05:40 +0000231 .. note::
232
Ethan Furman63c141c2013-10-18 00:27:39 -0700233 :func:`getmembers` will only return class attributes defined in the
234 metaclass when the argument is a class and those attributes have been
235 listed in the metaclass' custom :meth:`__dir__`.
Christian Heimes7f044312008-01-06 17:05:40 +0000236
Georg Brandl116aa622007-08-15 14:28:22 +0000237
238.. function:: getmoduleinfo(path)
239
Georg Brandlb30f3302011-01-06 09:23:56 +0000240 Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode, module_type)``
241 of values that describe how Python will interpret the file identified by
242 *path* if it is a module, or ``None`` if it would not be identified as a
243 module. In that tuple, *name* is the name of the module without the name of
244 any enclosing package, *suffix* is the trailing part of the file name (which
245 may not be a dot-delimited extension), *mode* is the :func:`open` mode that
246 would be used (``'r'`` or ``'rb'``), and *module_type* is an integer giving
247 the type of the module. *module_type* will have a value which can be
248 compared to the constants defined in the :mod:`imp` module; see the
249 documentation for that module for more information on module types.
Georg Brandl116aa622007-08-15 14:28:22 +0000250
Brett Cannoncb66eb02012-05-11 12:58:42 -0400251 .. deprecated:: 3.3
252 You may check the file path's suffix against the supported suffixes
253 listed in :mod:`importlib.machinery` to infer the same information.
254
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256.. function:: getmodulename(path)
257
258 Return the name of the module named by the file *path*, without including the
Nick Coghlan76e07702012-07-18 23:14:57 +1000259 names of enclosing packages. The file extension is checked against all of
260 the entries in :func:`importlib.machinery.all_suffixes`. If it matches,
261 the final path component is returned with the extension removed.
262 Otherwise, ``None`` is returned.
263
264 Note that this function *only* returns a meaningful name for actual
265 Python modules - paths that potentially refer to Python packages will
266 still return ``None``.
267
268 .. versionchanged:: 3.3
269 This function is now based directly on :mod:`importlib` rather than the
270 deprecated :func:`getmoduleinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272
273.. function:: ismodule(object)
274
275 Return true if the object is a module.
276
277
278.. function:: isclass(object)
279
Georg Brandl39cadc32010-10-15 16:53:24 +0000280 Return true if the object is a class, whether built-in or created in Python
281 code.
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283
284.. function:: ismethod(object)
285
Georg Brandl39cadc32010-10-15 16:53:24 +0000286 Return true if the object is a bound method written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000287
288
289.. function:: isfunction(object)
290
Georg Brandl39cadc32010-10-15 16:53:24 +0000291 Return true if the object is a Python function, which includes functions
292 created by a :term:`lambda` expression.
Georg Brandl116aa622007-08-15 14:28:22 +0000293
294
Christian Heimes7131fd92008-02-19 14:21:46 +0000295.. function:: isgeneratorfunction(object)
296
297 Return true if the object is a Python generator function.
298
299
300.. function:: isgenerator(object)
301
302 Return true if the object is a generator.
303
304
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400305.. function:: iscoroutinefunction(object)
306
Yury Selivanov5376ba92015-06-22 12:19:30 -0400307 Return true if the object is a :term:`coroutine function`
308 (a function defined with an :keyword:`async def` syntax).
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400309
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400310 .. versionadded:: 3.5
311
312
313.. function:: iscoroutine(object)
314
Yury Selivanov5376ba92015-06-22 12:19:30 -0400315 Return true if the object is a :term:`coroutine` created by an
316 :keyword:`async def` function.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400317
318 .. versionadded:: 3.5
319
320
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400321.. function:: isawaitable(object)
322
323 Return true if the object can be used in :keyword:`await` expression.
324
325 Can also be used to distinguish generator-based coroutines from regular
326 generators::
327
328 def gen():
329 yield
330 @types.coroutine
331 def gen_coro():
332 yield
333
334 assert not isawaitable(gen())
335 assert isawaitable(gen_coro())
336
337 .. versionadded:: 3.5
338
339
Georg Brandl116aa622007-08-15 14:28:22 +0000340.. function:: istraceback(object)
341
342 Return true if the object is a traceback.
343
344
345.. function:: isframe(object)
346
347 Return true if the object is a frame.
348
349
350.. function:: iscode(object)
351
352 Return true if the object is a code.
353
354
355.. function:: isbuiltin(object)
356
Georg Brandl39cadc32010-10-15 16:53:24 +0000357 Return true if the object is a built-in function or a bound built-in method.
Georg Brandl116aa622007-08-15 14:28:22 +0000358
359
360.. function:: isroutine(object)
361
362 Return true if the object is a user-defined or built-in function or method.
363
Georg Brandl39cadc32010-10-15 16:53:24 +0000364
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000365.. function:: isabstract(object)
366
367 Return true if the object is an abstract base class.
368
Georg Brandl116aa622007-08-15 14:28:22 +0000369
370.. function:: ismethoddescriptor(object)
371
Georg Brandl39cadc32010-10-15 16:53:24 +0000372 Return true if the object is a method descriptor, but not if
373 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
374 are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000375
Georg Brandle6bcc912008-05-12 18:05:20 +0000376 This, for example, is true of ``int.__add__``. An object passing this test
Martin Panterbae5d812016-06-18 03:57:31 +0000377 has a :meth:`~object.__get__` method but not a :meth:`~object.__set__`
378 method, but beyond that the set of attributes varies. A
379 :attr:`~definition.__name__` attribute is usually
Georg Brandle6bcc912008-05-12 18:05:20 +0000380 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Georg Brandl9afde1c2007-11-01 20:32:30 +0000382 Methods implemented via descriptors that also pass one of the other tests
383 return false from the :func:`ismethoddescriptor` test, simply because the
384 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000385 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387
388.. function:: isdatadescriptor(object)
389
390 Return true if the object is a data descriptor.
391
Martin Panterbae5d812016-06-18 03:57:31 +0000392 Data descriptors have both a :attr:`~object.__get__` and a :attr:`~object.__set__` method.
Georg Brandl9afde1c2007-11-01 20:32:30 +0000393 Examples are properties (defined in Python), getsets, and members. The
394 latter two are defined in C and there are more specific tests available for
395 those types, which is robust across Python implementations. Typically, data
Martin Panterbae5d812016-06-18 03:57:31 +0000396 descriptors will also have :attr:`~definition.__name__` and :attr:`__doc__` attributes
Georg Brandl9afde1c2007-11-01 20:32:30 +0000397 (properties, getsets, and members have both of these attributes), but this is
398 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000399
Georg Brandl116aa622007-08-15 14:28:22 +0000400
401.. function:: isgetsetdescriptor(object)
402
403 Return true if the object is a getset descriptor.
404
Georg Brandl495f7b52009-10-27 15:28:25 +0000405 .. impl-detail::
406
407 getsets are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000408 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000409 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000410
Georg Brandl116aa622007-08-15 14:28:22 +0000411
412.. function:: ismemberdescriptor(object)
413
414 Return true if the object is a member descriptor.
415
Georg Brandl495f7b52009-10-27 15:28:25 +0000416 .. impl-detail::
417
418 Member descriptors are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000419 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000420 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000421
Georg Brandl116aa622007-08-15 14:28:22 +0000422
423.. _inspect-source:
424
425Retrieving source code
426----------------------
427
Georg Brandl116aa622007-08-15 14:28:22 +0000428.. function:: getdoc(object)
429
Georg Brandl0c77a822008-06-10 16:37:50 +0000430 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300431 If the documentation string for an object is not provided and the object is
432 a class, a method, a property or a descriptor, retrieve the documentation
433 string from the inheritance hierarchy.
Georg Brandl116aa622007-08-15 14:28:22 +0000434
Berker Peksag4333d8b2015-07-30 18:06:09 +0300435 .. versionchanged:: 3.5
436 Documentation strings are now inherited if not overridden.
437
Georg Brandl116aa622007-08-15 14:28:22 +0000438
439.. function:: getcomments(object)
440
441 Return in a single string any lines of comments immediately preceding the
442 object's source code (for a class, function, or method), or at the top of the
443 Python source file (if the object is a module).
444
445
446.. function:: getfile(object)
447
448 Return the name of the (text or binary) file in which an object was defined.
449 This will fail with a :exc:`TypeError` if the object is a built-in module,
450 class, or function.
451
452
453.. function:: getmodule(object)
454
455 Try to guess which module an object was defined in.
456
457
458.. function:: getsourcefile(object)
459
460 Return the name of the Python source file in which an object was defined. This
461 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
462 function.
463
464
465.. function:: getsourcelines(object)
466
467 Return a list of source lines and starting line number for an object. The
468 argument may be a module, class, method, function, traceback, frame, or code
469 object. The source code is returned as a list of the lines corresponding to the
470 object and the line number indicates where in the original source file the first
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200471 line of code was found. An :exc:`OSError` is raised if the source code cannot
Georg Brandl116aa622007-08-15 14:28:22 +0000472 be retrieved.
473
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200474 .. versionchanged:: 3.3
475 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
476 former.
477
Georg Brandl116aa622007-08-15 14:28:22 +0000478
479.. function:: getsource(object)
480
481 Return the text of the source code for an object. The argument may be a module,
482 class, method, function, traceback, frame, or code object. The source code is
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200483 returned as a single string. An :exc:`OSError` is raised if the source code
Georg Brandl116aa622007-08-15 14:28:22 +0000484 cannot be retrieved.
485
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200486 .. versionchanged:: 3.3
487 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
488 former.
489
Georg Brandl116aa622007-08-15 14:28:22 +0000490
Georg Brandl0c77a822008-06-10 16:37:50 +0000491.. function:: cleandoc(doc)
492
493 Clean up indentation from docstrings that are indented to line up with blocks
Senthil Kumaranebd84e32016-05-29 20:36:58 -0700494 of code.
495
496 All leading whitespace is removed from the first line. Any leading whitespace
497 that can be uniformly removed from the second line onwards is removed. Empty
498 lines at the beginning and end are subsequently removed. Also, all tabs are
499 expanded to spaces.
Georg Brandl0c77a822008-06-10 16:37:50 +0000500
Georg Brandl0c77a822008-06-10 16:37:50 +0000501
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300502.. _inspect-signature-object:
503
Georg Brandle4717722012-08-14 09:45:28 +0200504Introspecting callables with the Signature object
505-------------------------------------------------
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300506
507.. versionadded:: 3.3
508
Georg Brandle4717722012-08-14 09:45:28 +0200509The Signature object represents the call signature of a callable object and its
510return annotation. To retrieve a Signature object, use the :func:`signature`
511function.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300512
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400513.. function:: signature(callable, \*, follow_wrapped=True)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300514
Georg Brandle4717722012-08-14 09:45:28 +0200515 Return a :class:`Signature` object for the given ``callable``::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300516
517 >>> from inspect import signature
518 >>> def foo(a, *, b:int, **kwargs):
519 ... pass
520
521 >>> sig = signature(foo)
522
523 >>> str(sig)
524 '(a, *, b:int, **kwargs)'
525
526 >>> str(sig.parameters['b'])
527 'b:int'
528
529 >>> sig.parameters['b'].annotation
530 <class 'int'>
531
Georg Brandle4717722012-08-14 09:45:28 +0200532 Accepts a wide range of python callables, from plain functions and classes to
533 :func:`functools.partial` objects.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300534
Larry Hastings5c661892014-01-24 06:17:25 -0800535 Raises :exc:`ValueError` if no signature can be provided, and
536 :exc:`TypeError` if that type of object is not supported.
537
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400538 .. versionadded:: 3.5
539 ``follow_wrapped`` parameter. Pass ``False`` to get a signature of
540 ``callable`` specifically (``callable.__wrapped__`` will not be used to
541 unwrap decorated callables.)
542
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300543 .. note::
544
Georg Brandle4717722012-08-14 09:45:28 +0200545 Some callables may not be introspectable in certain implementations of
Yury Selivanovd71e52f2014-01-30 00:22:57 -0500546 Python. For example, in CPython, some built-in functions defined in
547 C provide no metadata about their arguments.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300548
549
Yury Selivanov78356892014-01-30 00:10:54 -0500550.. class:: Signature(parameters=None, \*, return_annotation=Signature.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300551
Georg Brandle4717722012-08-14 09:45:28 +0200552 A Signature object represents the call signature of a function and its return
553 annotation. For each parameter accepted by the function it stores a
554 :class:`Parameter` object in its :attr:`parameters` collection.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300555
Yury Selivanov78356892014-01-30 00:10:54 -0500556 The optional *parameters* argument is a sequence of :class:`Parameter`
557 objects, which is validated to check that there are no parameters with
558 duplicate names, and that the parameters are in the right order, i.e.
559 positional-only first, then positional-or-keyword, and that parameters with
560 defaults follow parameters without defaults.
561
562 The optional *return_annotation* argument, can be an arbitrary Python object,
563 is the "return" annotation of the callable.
564
Georg Brandle4717722012-08-14 09:45:28 +0200565 Signature objects are *immutable*. Use :meth:`Signature.replace` to make a
566 modified copy.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300567
Yury Selivanov67d727e2014-03-29 13:24:14 -0400568 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400569 Signature objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400570
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300571 .. attribute:: Signature.empty
572
573 A special class-level marker to specify absence of a return annotation.
574
575 .. attribute:: Signature.parameters
576
577 An ordered mapping of parameters' names to the corresponding
578 :class:`Parameter` objects.
579
580 .. attribute:: Signature.return_annotation
581
Georg Brandle4717722012-08-14 09:45:28 +0200582 The "return" annotation for the callable. If the callable has no "return"
583 annotation, this attribute is set to :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300584
585 .. method:: Signature.bind(*args, **kwargs)
586
Georg Brandle4717722012-08-14 09:45:28 +0200587 Create a mapping from positional and keyword arguments to parameters.
588 Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
589 signature, or raises a :exc:`TypeError`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300590
591 .. method:: Signature.bind_partial(*args, **kwargs)
592
Georg Brandle4717722012-08-14 09:45:28 +0200593 Works the same way as :meth:`Signature.bind`, but allows the omission of
594 some required arguments (mimics :func:`functools.partial` behavior.)
595 Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
596 passed arguments do not match the signature.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300597
Ezio Melotti8429b672012-09-14 06:35:09 +0300598 .. method:: Signature.replace(*[, parameters][, return_annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300599
Georg Brandle4717722012-08-14 09:45:28 +0200600 Create a new Signature instance based on the instance replace was invoked
601 on. It is possible to pass different ``parameters`` and/or
602 ``return_annotation`` to override the corresponding properties of the base
603 signature. To remove return_annotation from the copied Signature, pass in
604 :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300605
606 ::
607
608 >>> def test(a, b):
609 ... pass
610 >>> sig = signature(test)
611 >>> new_sig = sig.replace(return_annotation="new return anno")
612 >>> str(new_sig)
613 "(a, b) -> 'new return anno'"
614
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400615 .. classmethod:: Signature.from_callable(obj, \*, follow_wrapped=True)
Yury Selivanovda396452014-03-27 12:09:24 -0400616
617 Return a :class:`Signature` (or its subclass) object for a given callable
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400618 ``obj``. Pass ``follow_wrapped=False`` to get a signature of ``obj``
619 without unwrapping its ``__wrapped__`` chain.
Yury Selivanovda396452014-03-27 12:09:24 -0400620
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400621 This method simplifies subclassing of :class:`Signature`::
Yury Selivanovda396452014-03-27 12:09:24 -0400622
623 class MySignature(Signature):
624 pass
625 sig = MySignature.from_callable(min)
626 assert isinstance(sig, MySignature)
627
Yury Selivanov232b9342014-03-29 13:18:30 -0400628 .. versionadded:: 3.5
629
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300630
Yury Selivanov78356892014-01-30 00:10:54 -0500631.. class:: Parameter(name, kind, \*, default=Parameter.empty, annotation=Parameter.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300632
Georg Brandle4717722012-08-14 09:45:28 +0200633 Parameter objects are *immutable*. Instead of modifying a Parameter object,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300634 you can use :meth:`Parameter.replace` to create a modified copy.
635
Yury Selivanov67d727e2014-03-29 13:24:14 -0400636 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400637 Parameter objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400638
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300639 .. attribute:: Parameter.empty
640
Georg Brandle4717722012-08-14 09:45:28 +0200641 A special class-level marker to specify absence of default values and
642 annotations.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300643
644 .. attribute:: Parameter.name
645
Yury Selivanov2393dca2014-01-27 15:07:58 -0500646 The name of the parameter as a string. The name must be a valid
647 Python identifier.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300648
649 .. attribute:: Parameter.default
650
Georg Brandle4717722012-08-14 09:45:28 +0200651 The default value for the parameter. If the parameter has no default
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300652 value, this attribute is set to :attr:`Parameter.empty`.
653
654 .. attribute:: Parameter.annotation
655
Georg Brandle4717722012-08-14 09:45:28 +0200656 The annotation for the parameter. If the parameter has no annotation,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300657 this attribute is set to :attr:`Parameter.empty`.
658
659 .. attribute:: Parameter.kind
660
Georg Brandle4717722012-08-14 09:45:28 +0200661 Describes how argument values are bound to the parameter. Possible values
662 (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300663
Georg Brandl44ea77b2013-03-28 13:28:44 +0100664 .. tabularcolumns:: |l|L|
665
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300666 +------------------------+----------------------------------------------+
667 | Name | Meaning |
668 +========================+==============================================+
669 | *POSITIONAL_ONLY* | Value must be supplied as a positional |
670 | | argument. |
671 | | |
672 | | Python has no explicit syntax for defining |
673 | | positional-only parameters, but many built-in|
674 | | and extension module functions (especially |
675 | | those that accept only one or two parameters)|
676 | | accept them. |
677 +------------------------+----------------------------------------------+
678 | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
679 | | positional argument (this is the standard |
680 | | binding behaviour for functions implemented |
681 | | in Python.) |
682 +------------------------+----------------------------------------------+
683 | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
684 | | bound to any other parameter. This |
685 | | corresponds to a ``*args`` parameter in a |
686 | | Python function definition. |
687 +------------------------+----------------------------------------------+
688 | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
689 | | Keyword only parameters are those which |
690 | | appear after a ``*`` or ``*args`` entry in a |
691 | | Python function definition. |
692 +------------------------+----------------------------------------------+
693 | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
694 | | to any other parameter. This corresponds to a|
695 | | ``**kwargs`` parameter in a Python function |
696 | | definition. |
697 +------------------------+----------------------------------------------+
698
Andrew Svetloveed18082012-08-13 18:23:54 +0300699 Example: print all keyword-only arguments without default values::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300700
701 >>> def foo(a, b, *, c, d=10):
702 ... pass
703
704 >>> sig = signature(foo)
705 >>> for param in sig.parameters.values():
706 ... if (param.kind == param.KEYWORD_ONLY and
707 ... param.default is param.empty):
708 ... print('Parameter:', param)
709 Parameter: c
710
Ezio Melotti8429b672012-09-14 06:35:09 +0300711 .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300712
Georg Brandle4717722012-08-14 09:45:28 +0200713 Create a new Parameter instance based on the instance replaced was invoked
714 on. To override a :class:`Parameter` attribute, pass the corresponding
715 argument. To remove a default value or/and an annotation from a
716 Parameter, pass :attr:`Parameter.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300717
718 ::
719
720 >>> from inspect import Parameter
721 >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
722 >>> str(param)
723 'foo=42'
724
725 >>> str(param.replace()) # Will create a shallow copy of 'param'
726 'foo=42'
727
728 >>> str(param.replace(default=Parameter.empty, annotation='spam'))
729 "foo:'spam'"
730
Yury Selivanov2393dca2014-01-27 15:07:58 -0500731 .. versionchanged:: 3.4
732 In Python 3.3 Parameter objects were allowed to have ``name`` set
733 to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``.
734 This is no longer permitted.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300735
736.. class:: BoundArguments
737
738 Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
739 Holds the mapping of arguments to the function's parameters.
740
741 .. attribute:: BoundArguments.arguments
742
743 An ordered, mutable mapping (:class:`collections.OrderedDict`) of
Georg Brandle4717722012-08-14 09:45:28 +0200744 parameters' names to arguments' values. Contains only explicitly bound
745 arguments. Changes in :attr:`arguments` will reflect in :attr:`args` and
746 :attr:`kwargs`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300747
Georg Brandle4717722012-08-14 09:45:28 +0200748 Should be used in conjunction with :attr:`Signature.parameters` for any
749 argument processing purposes.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300750
751 .. note::
752
753 Arguments for which :meth:`Signature.bind` or
754 :meth:`Signature.bind_partial` relied on a default value are skipped.
Yury Selivanovb907a512015-05-16 13:45:09 -0400755 However, if needed, use :meth:`BoundArguments.apply_defaults` to add
756 them.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300757
758 .. attribute:: BoundArguments.args
759
Georg Brandle4717722012-08-14 09:45:28 +0200760 A tuple of positional arguments values. Dynamically computed from the
761 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300762
763 .. attribute:: BoundArguments.kwargs
764
Georg Brandle4717722012-08-14 09:45:28 +0200765 A dict of keyword arguments values. Dynamically computed from the
766 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300767
Yury Selivanov82796192015-05-14 14:14:02 -0400768 .. attribute:: BoundArguments.signature
769
770 A reference to the parent :class:`Signature` object.
771
Yury Selivanovb907a512015-05-16 13:45:09 -0400772 .. method:: BoundArguments.apply_defaults()
773
774 Set default values for missing arguments.
775
776 For variable-positional arguments (``*args``) the default is an
777 empty tuple.
778
779 For variable-keyword arguments (``**kwargs``) the default is an
780 empty dict.
781
782 ::
783
784 >>> def foo(a, b='ham', *args): pass
785 >>> ba = inspect.signature(foo).bind('spam')
786 >>> ba.apply_defaults()
787 >>> ba.arguments
788 OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])
789
Berker Peksag5b3df5b2015-05-16 23:29:31 +0300790 .. versionadded:: 3.5
791
Georg Brandle4717722012-08-14 09:45:28 +0200792 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
793 functions::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300794
795 def test(a, *, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300796 ...
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300797
798 sig = signature(test)
799 ba = sig.bind(10, b=20)
800 test(*ba.args, **ba.kwargs)
801
802
Georg Brandle4717722012-08-14 09:45:28 +0200803.. seealso::
804
805 :pep:`362` - Function Signature Object.
806 The detailed specification, implementation details and examples.
807
808
Georg Brandl116aa622007-08-15 14:28:22 +0000809.. _inspect-classes-functions:
810
811Classes and functions
812---------------------
813
Georg Brandl3dd33882009-06-01 17:35:27 +0000814.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000815
816 Arrange the given list of classes into a hierarchy of nested lists. Where a
817 nested list appears, it contains classes derived from the class whose entry
818 immediately precedes the list. Each entry is a 2-tuple containing a class and a
819 tuple of its base classes. If the *unique* argument is true, exactly one entry
820 appears in the returned structure for each class in the given list. Otherwise,
821 classes using multiple inheritance and their descendants will appear multiple
822 times.
823
824
825.. function:: getargspec(func)
826
Georg Brandl82402752010-01-09 09:48:46 +0000827 Get the names and default values of a Python function's arguments. A
Georg Brandlb30f3302011-01-06 09:23:56 +0000828 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
829 returned. *args* is a list of the argument names. *varargs* and *keywords*
830 are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700831 tuple of default argument values or ``None`` if there are no default
832 arguments; if this tuple has *n* elements, they correspond to the last
833 *n* elements listed in *args*.
Georg Brandl138bcb52007-09-12 19:04:21 +0000834
835 .. deprecated:: 3.0
Yury Selivanov945fff42015-05-22 16:28:05 -0400836 Use :func:`signature` and
837 :ref:`Signature Object <inspect-signature-object>`, which provide a
Yury Selivanova7c159d2016-01-11 21:04:50 -0500838 better introspecting API for callables.
Georg Brandl138bcb52007-09-12 19:04:21 +0000839
840
841.. function:: getfullargspec(func)
842
Georg Brandl82402752010-01-09 09:48:46 +0000843 Get the names and default values of a Python function's arguments. A
844 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000845
Georg Brandl3dd33882009-06-01 17:35:27 +0000846 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
847 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000848
849 *args* is a list of the argument names. *varargs* and *varkw* are the names
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700850 of the ``*`` and ``**`` arguments or ``None``. *defaults* is an *n*-tuple
851 of the default values of the last *n* arguments, or ``None`` if there are no
852 default arguments. *kwonlyargs* is a list of
Georg Brandl138bcb52007-09-12 19:04:21 +0000853 keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
854 from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
855 names to annotations.
856
857 The first four items in the tuple correspond to :func:`getargspec`.
Georg Brandl116aa622007-08-15 14:28:22 +0000858
Nick Coghlan16355782014-03-08 16:36:37 +1000859 .. versionchanged:: 3.4
860 This function is now based on :func:`signature`, but still ignores
861 ``__wrapped__`` attributes and includes the already bound first
862 parameter in the signature output for bound methods.
863
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400864 .. deprecated:: 3.5
865 Use :func:`signature` and
866 :ref:`Signature Object <inspect-signature-object>`, which provide a
867 better introspecting API for callables.
868
Georg Brandl116aa622007-08-15 14:28:22 +0000869
870.. function:: getargvalues(frame)
871
Georg Brandl3dd33882009-06-01 17:35:27 +0000872 Get information about arguments passed into a particular frame. A
873 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000874 returned. *args* is a list of the argument names. *varargs* and *keywords*
875 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000876 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000877
Yury Selivanov945fff42015-05-22 16:28:05 -0400878 .. deprecated:: 3.5
879 Use :func:`signature` and
880 :ref:`Signature Object <inspect-signature-object>`, which provide a
881 better introspecting API for callables.
882
Georg Brandl116aa622007-08-15 14:28:22 +0000883
Andrew Svetlov735d3172012-10-27 00:28:20 +0300884.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Georg Brandl116aa622007-08-15 14:28:22 +0000885
Michael Foord3af125a2012-04-21 18:22:28 +0100886 Format a pretty argument spec from the values returned by
887 :func:`getargspec` or :func:`getfullargspec`.
888
889 The first seven arguments are (``args``, ``varargs``, ``varkw``,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100890 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
Andrew Svetlov735d3172012-10-27 00:28:20 +0300891
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100892 The other six arguments are functions that are called to turn argument names,
893 ``*`` argument name, ``**`` argument name, default values, return annotation
894 and individual annotations into strings, respectively.
895
896 For example:
897
898 >>> from inspect import formatargspec, getfullargspec
899 >>> def f(a: int, b: float):
900 ... pass
901 ...
902 >>> formatargspec(*getfullargspec(f))
903 '(a: int, b: float)'
Georg Brandl116aa622007-08-15 14:28:22 +0000904
Yury Selivanov945fff42015-05-22 16:28:05 -0400905 .. deprecated:: 3.5
906 Use :func:`signature` and
907 :ref:`Signature Object <inspect-signature-object>`, which provide a
908 better introspecting API for callables.
909
Georg Brandl116aa622007-08-15 14:28:22 +0000910
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000911.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000912
913 Format a pretty argument spec from the four values returned by
914 :func:`getargvalues`. The format\* arguments are the corresponding optional
915 formatting functions that are called to turn names and values into strings.
916
Yury Selivanov945fff42015-05-22 16:28:05 -0400917 .. deprecated:: 3.5
918 Use :func:`signature` and
919 :ref:`Signature Object <inspect-signature-object>`, which provide a
920 better introspecting API for callables.
921
Georg Brandl116aa622007-08-15 14:28:22 +0000922
923.. function:: getmro(cls)
924
925 Return a tuple of class cls's base classes, including cls, in method resolution
926 order. No class appears more than once in this tuple. Note that the method
927 resolution order depends on cls's type. Unless a very peculiar user-defined
928 metatype is in use, cls will be the first element of the tuple.
929
930
Benjamin Peterson3a990c62014-01-02 12:22:30 -0600931.. function:: getcallargs(func, *args, **kwds)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000932
933 Bind the *args* and *kwds* to the argument names of the Python function or
934 method *func*, as if it was called with them. For bound methods, bind also the
935 first argument (typically named ``self``) to the associated instance. A dict
936 is returned, mapping the argument names (including the names of the ``*`` and
937 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
938 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
939 an exception because of incompatible signature, an exception of the same type
940 and the same or similar message is raised. For example::
941
942 >>> from inspect import getcallargs
943 >>> def f(a, b=1, *pos, **named):
944 ... pass
Andrew Svetlove939f382012-08-09 13:25:32 +0300945 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
946 True
947 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
948 True
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000949 >>> getcallargs(f)
950 Traceback (most recent call last):
951 ...
Andrew Svetlove939f382012-08-09 13:25:32 +0300952 TypeError: f() missing 1 required positional argument: 'a'
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000953
954 .. versionadded:: 3.2
955
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400956 .. deprecated:: 3.5
957 Use :meth:`Signature.bind` and :meth:`Signature.bind_partial` instead.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300958
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000959
Nick Coghlan2f92e542012-06-23 19:39:55 +1000960.. function:: getclosurevars(func)
961
962 Get the mapping of external name references in a Python function or
963 method *func* to their current values. A
964 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
965 is returned. *nonlocals* maps referenced names to lexical closure
966 variables, *globals* to the function's module globals and *builtins* to
967 the builtins visible from the function body. *unbound* is the set of names
968 referenced in the function that could not be resolved at all given the
969 current module globals and builtins.
970
971 :exc:`TypeError` is raised if *func* is not a Python function or method.
972
973 .. versionadded:: 3.3
974
975
Nick Coghlane8c45d62013-07-28 20:00:01 +1000976.. function:: unwrap(func, *, stop=None)
977
978 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
979 attributes returning the last object in the chain.
980
981 *stop* is an optional callback accepting an object in the wrapper chain
982 as its sole argument that allows the unwrapping to be terminated early if
983 the callback returns a true value. If the callback never returns a true
984 value, the last object in the chain is returned as usual. For example,
985 :func:`signature` uses this to stop unwrapping if any object in the
986 chain has a ``__signature__`` attribute defined.
987
988 :exc:`ValueError` is raised if a cycle is encountered.
989
990 .. versionadded:: 3.4
991
992
Georg Brandl116aa622007-08-15 14:28:22 +0000993.. _inspect-stack:
994
995The interpreter stack
996---------------------
997
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400998When the following functions return "frame records," each record is a
999:term:`named tuple`
1000``FrameInfo(frame, filename, lineno, function, code_context, index)``.
1001The tuple contains the frame object, the filename, the line number of the
1002current line,
Georg Brandl116aa622007-08-15 14:28:22 +00001003the function name, a list of lines of context from the source code, and the
1004index of the current line within that list.
1005
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001006.. versionchanged:: 3.5
1007 Return a named tuple instead of a tuple.
1008
Georg Brandle720c0a2009-04-27 16:20:50 +00001009.. note::
Georg Brandl116aa622007-08-15 14:28:22 +00001010
1011 Keeping references to frame objects, as found in the first element of the frame
1012 records these functions return, can cause your program to create reference
1013 cycles. Once a reference cycle has been created, the lifespan of all objects
1014 which can be accessed from the objects which form the cycle can become much
1015 longer even if Python's optional cycle detector is enabled. If such cycles must
1016 be created, it is important to ensure they are explicitly broken to avoid the
1017 delayed destruction of objects and increased memory consumption which occurs.
1018
1019 Though the cycle detector will catch these, destruction of the frames (and local
1020 variables) can be made deterministic by removing the cycle in a
1021 :keyword:`finally` clause. This is also important if the cycle detector was
1022 disabled when Python was compiled or using :func:`gc.disable`. For example::
1023
1024 def handle_stackframe_without_leak():
1025 frame = inspect.currentframe()
1026 try:
1027 # do something with the frame
1028 finally:
1029 del frame
1030
Antoine Pitrou58720d62013-08-05 23:26:40 +02001031 If you want to keep the frame around (for example to print a traceback
1032 later), you can also break reference cycles by using the
1033 :meth:`frame.clear` method.
1034
Georg Brandl116aa622007-08-15 14:28:22 +00001035The optional *context* argument supported by most of these functions specifies
1036the number of lines of context to return, which are centered around the current
1037line.
1038
1039
Georg Brandl3dd33882009-06-01 17:35:27 +00001040.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001041
Georg Brandl48310cd2009-01-03 21:18:54 +00001042 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +00001043 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +00001044
1045
Georg Brandl3dd33882009-06-01 17:35:27 +00001046.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001047
1048 Get a list of frame records for a frame and all outer frames. These frames
1049 represent the calls that lead to the creation of *frame*. The first entry in the
1050 returned list represents *frame*; the last entry represents the outermost call
1051 on *frame*'s stack.
1052
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001053 .. versionchanged:: 3.5
1054 A list of :term:`named tuples <named tuple>`
1055 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1056 is returned.
1057
Georg Brandl116aa622007-08-15 14:28:22 +00001058
Georg Brandl3dd33882009-06-01 17:35:27 +00001059.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001060
1061 Get a list of frame records for a traceback's frame and all inner frames. These
1062 frames represent calls made as a consequence of *frame*. The first entry in the
1063 list represents *traceback*; the last entry represents where the exception was
1064 raised.
1065
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001066 .. versionchanged:: 3.5
1067 A list of :term:`named tuples <named tuple>`
1068 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1069 is returned.
1070
Georg Brandl116aa622007-08-15 14:28:22 +00001071
1072.. function:: currentframe()
1073
1074 Return the frame object for the caller's stack frame.
1075
Georg Brandl495f7b52009-10-27 15:28:25 +00001076 .. impl-detail::
1077
1078 This function relies on Python stack frame support in the interpreter,
1079 which isn't guaranteed to exist in all implementations of Python. If
1080 running in an implementation without Python stack frame support this
1081 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001082
Georg Brandl116aa622007-08-15 14:28:22 +00001083
Georg Brandl3dd33882009-06-01 17:35:27 +00001084.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001085
1086 Return a list of frame records for the caller's stack. The first entry in the
1087 returned list represents the caller; the last entry represents the outermost
1088 call on the stack.
1089
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001090 .. versionchanged:: 3.5
1091 A list of :term:`named tuples <named tuple>`
1092 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1093 is returned.
1094
Georg Brandl116aa622007-08-15 14:28:22 +00001095
Georg Brandl3dd33882009-06-01 17:35:27 +00001096.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001097
1098 Return a list of frame records for the stack between the current frame and the
1099 frame in which an exception currently being handled was raised in. The first
1100 entry in the list represents the caller; the last entry represents where the
1101 exception was raised.
1102
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001103 .. versionchanged:: 3.5
1104 A list of :term:`named tuples <named tuple>`
1105 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1106 is returned.
1107
Michael Foord95fc51d2010-11-20 15:07:30 +00001108
1109Fetching attributes statically
1110------------------------------
1111
1112Both :func:`getattr` and :func:`hasattr` can trigger code execution when
1113fetching or checking for the existence of attributes. Descriptors, like
1114properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
1115may be called.
1116
1117For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +02001118can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +00001119but avoids executing code when it fetches attributes.
1120
1121.. function:: getattr_static(obj, attr, default=None)
1122
1123 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +02001124 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +00001125
1126 Note: this function may not be able to retrieve all attributes
1127 that getattr can fetch (like dynamically created attributes)
1128 and may find attributes that getattr can't (like descriptors
1129 that raise AttributeError). It can also return descriptors objects
1130 instead of instance members.
1131
Serhiy Storchakabfdcd432013-10-13 23:09:14 +03001132 If the instance :attr:`~object.__dict__` is shadowed by another member (for
1133 example a property) then this function will be unable to find instance
1134 members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001135
Michael Foorddcebe0f2011-03-15 19:20:44 -04001136 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +00001137
Éric Araujo941afed2011-09-01 02:47:34 +02001138:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +00001139getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +00001140is returned instead of the underlying attribute.
1141
1142You can handle these with code like the following. Note that
1143for arbitrary getset descriptors invoking these may trigger
1144code execution::
1145
1146 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +00001147 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +00001148 __slots__ = ['foo']
1149
1150 slot_descriptor = type(_foo.foo)
1151 getset_descriptor = type(type(open(__file__)).name)
1152 wrapper_descriptor = type(str.__dict__['__add__'])
1153 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
1154
1155 result = getattr_static(some_object, 'foo')
1156 if type(result) in descriptor_types:
1157 try:
1158 result = result.__get__()
1159 except AttributeError:
1160 # descriptors can raise AttributeError to
1161 # indicate there is no underlying value
1162 # in which case the descriptor itself will
1163 # have to do
1164 pass
Nick Coghlane0f04652010-11-21 03:44:04 +00001165
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001166
Yury Selivanov5376ba92015-06-22 12:19:30 -04001167Current State of Generators and Coroutines
1168------------------------------------------
Nick Coghlane0f04652010-11-21 03:44:04 +00001169
1170When implementing coroutine schedulers and for other advanced uses of
1171generators, it is useful to determine whether a generator is currently
1172executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001173terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +00001174generator to be determined easily.
1175
1176.. function:: getgeneratorstate(generator)
1177
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001178 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +00001179
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001180 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +00001181 * GEN_CREATED: Waiting to start execution.
1182 * GEN_RUNNING: Currently being executed by the interpreter.
1183 * GEN_SUSPENDED: Currently suspended at a yield expression.
1184 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +00001185
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001186 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001187
Yury Selivanov5376ba92015-06-22 12:19:30 -04001188.. function:: getcoroutinestate(coroutine)
1189
1190 Get current state of a coroutine object. The function is intended to be
1191 used with coroutine objects created by :keyword:`async def` functions, but
1192 will accept any coroutine-like object that has ``cr_running`` and
1193 ``cr_frame`` attributes.
1194
1195 Possible states are:
1196 * CORO_CREATED: Waiting to start execution.
1197 * CORO_RUNNING: Currently being executed by the interpreter.
1198 * CORO_SUSPENDED: Currently suspended at an await expression.
1199 * CORO_CLOSED: Execution has completed.
1200
1201 .. versionadded:: 3.5
1202
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001203The current internal state of the generator can also be queried. This is
1204mostly useful for testing purposes, to ensure that internal state is being
1205updated as expected:
1206
1207.. function:: getgeneratorlocals(generator)
1208
1209 Get the mapping of live local variables in *generator* to their current
1210 values. A dictionary is returned that maps from variable names to values.
1211 This is the equivalent of calling :func:`locals` in the body of the
1212 generator, and all the same caveats apply.
1213
1214 If *generator* is a :term:`generator` with no currently associated frame,
1215 then an empty dictionary is returned. :exc:`TypeError` is raised if
1216 *generator* is not a Python generator object.
1217
1218 .. impl-detail::
1219
1220 This function relies on the generator exposing a Python stack frame
1221 for introspection, which isn't guaranteed to be the case in all
1222 implementations of Python. In such cases, this function will always
1223 return an empty dictionary.
1224
1225 .. versionadded:: 3.3
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001226
Yury Selivanov5376ba92015-06-22 12:19:30 -04001227.. function:: getcoroutinelocals(coroutine)
1228
1229 This function is analogous to :func:`~inspect.getgeneratorlocals`, but
1230 works for coroutine objects created by :keyword:`async def` functions.
1231
1232 .. versionadded:: 3.5
1233
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001234
Nick Coghlan367df122013-10-27 01:57:34 +10001235.. _inspect-module-cli:
1236
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001237Command Line Interface
1238----------------------
1239
1240The :mod:`inspect` module also provides a basic introspection capability
1241from the command line.
1242
1243.. program:: inspect
1244
1245By default, accepts the name of a module and prints the source of that
1246module. A class or function within the module can be printed instead by
1247appended a colon and the qualified name of the target object.
1248
1249.. cmdoption:: --details
1250
1251 Print information about the specified object rather than the source code