blob: ff628de1bd50c434509e6acf7456ebb7b38e0365 [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.
6.. moduleauthor:: Ka-Ping Yee <ping@lfw.org>
7.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
8
Raymond Hettinger469271d2011-01-27 20:38:46 +00009**Source code:** :source:`Lib/inspect.py`
10
11--------------
Georg Brandl116aa622007-08-15 14:28:22 +000012
Georg Brandl116aa622007-08-15 14:28:22 +000013The :mod:`inspect` module provides several useful functions to help get
14information about live objects such as modules, classes, methods, functions,
15tracebacks, frame objects, and code objects. For example, it can help you
16examine the contents of a class, retrieve the source code of a method, extract
17and format the argument list for a function, or get all the information you need
18to display a detailed traceback.
19
20There are four main kinds of services provided by this module: type checking,
21getting source code, inspecting classes and functions, and examining the
22interpreter stack.
23
24
25.. _inspect-types:
26
27Types and members
28-----------------
29
30The :func:`getmembers` function retrieves the members of an object such as a
Yury Selivanov59a3b672015-06-30 22:06:42 -040031class or module. The functions whose names begin with "is" are mainly
Georg Brandl116aa622007-08-15 14:28:22 +000032provided as convenient choices for the second argument to :func:`getmembers`.
33They also help you determine when you can expect to find the following special
34attributes:
35
Georg Brandl55ac8f02007-09-01 13:51:09 +000036+-----------+-----------------+---------------------------+
37| Type | Attribute | Description |
38+===========+=================+===========================+
39| module | __doc__ | documentation string |
40+-----------+-----------------+---------------------------+
41| | __file__ | filename (missing for |
42| | | built-in modules) |
43+-----------+-----------------+---------------------------+
44| class | __doc__ | documentation string |
45+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -040046| | __name__ | name with which this |
47| | | class was defined |
48+-----------+-----------------+---------------------------+
49| | __qualname__ | qualified name |
50+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +000051| | __module__ | name of module in which |
52| | | this class was defined |
53+-----------+-----------------+---------------------------+
54| method | __doc__ | documentation string |
55+-----------+-----------------+---------------------------+
56| | __name__ | name with which this |
57| | | method was defined |
58+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -040059| | __qualname__ | qualified name |
60+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000061| | __func__ | function object |
Georg Brandl55ac8f02007-09-01 13:51:09 +000062| | | containing implementation |
63| | | of method |
64+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000065| | __self__ | instance to which this |
Georg Brandl55ac8f02007-09-01 13:51:09 +000066| | | method is bound, or |
67| | | ``None`` |
68+-----------+-----------------+---------------------------+
69| function | __doc__ | documentation string |
70+-----------+-----------------+---------------------------+
71| | __name__ | name with which this |
72| | | function was defined |
73+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -040074| | __qualname__ | qualified name |
75+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +000076| | __code__ | code object containing |
77| | | compiled function |
Georg Brandl9afde1c2007-11-01 20:32:30 +000078| | | :term:`bytecode` |
Georg Brandl55ac8f02007-09-01 13:51:09 +000079+-----------+-----------------+---------------------------+
80| | __defaults__ | tuple of any default |
Yury Selivanovea2d66e2014-01-27 14:26:28 -050081| | | values for positional or |
82| | | keyword parameters |
83+-----------+-----------------+---------------------------+
84| | __kwdefaults__ | mapping of any default |
85| | | values for keyword-only |
86| | | parameters |
Georg Brandl55ac8f02007-09-01 13:51:09 +000087+-----------+-----------------+---------------------------+
88| | __globals__ | global namespace in which |
89| | | this function was defined |
90+-----------+-----------------+---------------------------+
Yury Selivanovc62162d2015-10-31 13:29:15 -040091| | __annotations__ | mapping of parameters |
92| | | names to annotations; |
93| | | ``"return"`` key is |
94| | | reserved for return |
95| | | annotations. |
96+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +000097| traceback | tb_frame | frame object at this |
98| | | level |
99+-----------+-----------------+---------------------------+
100| | tb_lasti | index of last attempted |
101| | | instruction in bytecode |
102+-----------+-----------------+---------------------------+
103| | tb_lineno | current line number in |
104| | | Python source code |
105+-----------+-----------------+---------------------------+
106| | tb_next | next inner traceback |
107| | | object (called by this |
108| | | level) |
109+-----------+-----------------+---------------------------+
110| frame | f_back | next outer frame object |
111| | | (this frame's caller) |
112+-----------+-----------------+---------------------------+
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000113| | f_builtins | builtins namespace seen |
Georg Brandl55ac8f02007-09-01 13:51:09 +0000114| | | by this frame |
115+-----------+-----------------+---------------------------+
116| | f_code | code object being |
117| | | executed in this frame |
118+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000119| | f_globals | global namespace seen by |
120| | | this frame |
121+-----------+-----------------+---------------------------+
122| | f_lasti | index of last attempted |
123| | | instruction in bytecode |
124+-----------+-----------------+---------------------------+
125| | f_lineno | current line number in |
126| | | Python source code |
127+-----------+-----------------+---------------------------+
128| | f_locals | local namespace seen by |
129| | | this frame |
130+-----------+-----------------+---------------------------+
131| | f_restricted | 0 or 1 if frame is in |
132| | | restricted execution mode |
133+-----------+-----------------+---------------------------+
134| | f_trace | tracing function for this |
135| | | frame, or ``None`` |
136+-----------+-----------------+---------------------------+
137| code | co_argcount | number of arguments (not |
138| | | including \* or \*\* |
139| | | args) |
140+-----------+-----------------+---------------------------+
141| | co_code | string of raw compiled |
142| | | bytecode |
143+-----------+-----------------+---------------------------+
144| | co_consts | tuple of constants used |
145| | | in the bytecode |
146+-----------+-----------------+---------------------------+
147| | co_filename | name of file in which |
148| | | this code object was |
149| | | created |
150+-----------+-----------------+---------------------------+
151| | co_firstlineno | number of first line in |
152| | | Python source code |
153+-----------+-----------------+---------------------------+
154| | co_flags | bitmap: 1=optimized ``|`` |
155| | | 2=newlocals ``|`` 4=\*arg |
156| | | ``|`` 8=\*\*arg |
157+-----------+-----------------+---------------------------+
158| | co_lnotab | encoded mapping of line |
159| | | numbers to bytecode |
160| | | indices |
161+-----------+-----------------+---------------------------+
162| | co_name | name with which this code |
163| | | object was defined |
164+-----------+-----------------+---------------------------+
165| | co_names | tuple of names of local |
166| | | variables |
167+-----------+-----------------+---------------------------+
168| | co_nlocals | number of local variables |
169+-----------+-----------------+---------------------------+
170| | co_stacksize | virtual machine stack |
171| | | space required |
172+-----------+-----------------+---------------------------+
173| | co_varnames | tuple of names of |
174| | | arguments and local |
175| | | variables |
176+-----------+-----------------+---------------------------+
Victor Stinner40ee3012014-06-16 15:59:28 +0200177| generator | __name__ | name |
178+-----------+-----------------+---------------------------+
179| | __qualname__ | qualified name |
180+-----------+-----------------+---------------------------+
181| | gi_frame | frame |
182+-----------+-----------------+---------------------------+
183| | gi_running | is the generator running? |
184+-----------+-----------------+---------------------------+
185| | gi_code | code |
186+-----------+-----------------+---------------------------+
Yury Selivanovc135f0a2015-08-17 13:02:42 -0400187| | gi_yieldfrom | object being iterated by |
188| | | ``yield from``, or |
189| | | ``None`` |
190+-----------+-----------------+---------------------------+
Yury Selivanov5376ba92015-06-22 12:19:30 -0400191| coroutine | __name__ | name |
192+-----------+-----------------+---------------------------+
193| | __qualname__ | qualified name |
194+-----------+-----------------+---------------------------+
Yury Selivanove13f8f32015-07-03 00:23:30 -0400195| | cr_await | object being awaited on, |
196| | | or ``None`` |
197+-----------+-----------------+---------------------------+
Yury Selivanov5376ba92015-06-22 12:19:30 -0400198| | cr_frame | frame |
199+-----------+-----------------+---------------------------+
200| | cr_running | is the coroutine running? |
201+-----------+-----------------+---------------------------+
202| | cr_code | code |
203+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000204| builtin | __doc__ | documentation string |
205+-----------+-----------------+---------------------------+
206| | __name__ | original name of this |
207| | | function or method |
208+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -0400209| | __qualname__ | qualified name |
210+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000211| | __self__ | instance to which a |
212| | | method is bound, or |
213| | | ``None`` |
214+-----------+-----------------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000215
Victor Stinner40ee3012014-06-16 15:59:28 +0200216.. versionchanged:: 3.5
217
Yury Selivanov5fbad3c2015-08-17 13:04:41 -0400218 Add ``__qualname__`` and ``gi_yieldfrom`` attributes to generators.
219
220 The ``__name__`` attribute of generators is now set from the function
221 name, instead of the code name, and it can now be modified.
Victor Stinner40ee3012014-06-16 15:59:28 +0200222
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224.. function:: getmembers(object[, predicate])
225
226 Return all the members of an object in a list of (name, value) pairs sorted by
227 name. If the optional *predicate* argument is supplied, only members for which
228 the predicate returns a true value are included.
229
Christian Heimes7f044312008-01-06 17:05:40 +0000230 .. note::
231
Ethan Furman63c141c2013-10-18 00:27:39 -0700232 :func:`getmembers` will only return class attributes defined in the
233 metaclass when the argument is a class and those attributes have been
234 listed in the metaclass' custom :meth:`__dir__`.
Christian Heimes7f044312008-01-06 17:05:40 +0000235
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237.. function:: getmoduleinfo(path)
238
Georg Brandlb30f3302011-01-06 09:23:56 +0000239 Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode, module_type)``
240 of values that describe how Python will interpret the file identified by
241 *path* if it is a module, or ``None`` if it would not be identified as a
242 module. In that tuple, *name* is the name of the module without the name of
243 any enclosing package, *suffix* is the trailing part of the file name (which
244 may not be a dot-delimited extension), *mode* is the :func:`open` mode that
245 would be used (``'r'`` or ``'rb'``), and *module_type* is an integer giving
246 the type of the module. *module_type* will have a value which can be
247 compared to the constants defined in the :mod:`imp` module; see the
248 documentation for that module for more information on module types.
Georg Brandl116aa622007-08-15 14:28:22 +0000249
Brett Cannoncb66eb02012-05-11 12:58:42 -0400250 .. deprecated:: 3.3
251 You may check the file path's suffix against the supported suffixes
252 listed in :mod:`importlib.machinery` to infer the same information.
253
Georg Brandl116aa622007-08-15 14:28:22 +0000254
255.. function:: getmodulename(path)
256
257 Return the name of the module named by the file *path*, without including the
Nick Coghlan76e07702012-07-18 23:14:57 +1000258 names of enclosing packages. The file extension is checked against all of
259 the entries in :func:`importlib.machinery.all_suffixes`. If it matches,
260 the final path component is returned with the extension removed.
261 Otherwise, ``None`` is returned.
262
263 Note that this function *only* returns a meaningful name for actual
264 Python modules - paths that potentially refer to Python packages will
265 still return ``None``.
266
267 .. versionchanged:: 3.3
268 This function is now based directly on :mod:`importlib` rather than the
269 deprecated :func:`getmoduleinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000270
271
272.. function:: ismodule(object)
273
274 Return true if the object is a module.
275
276
277.. function:: isclass(object)
278
Georg Brandl39cadc32010-10-15 16:53:24 +0000279 Return true if the object is a class, whether built-in or created in Python
280 code.
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282
283.. function:: ismethod(object)
284
Georg Brandl39cadc32010-10-15 16:53:24 +0000285 Return true if the object is a bound method written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287
288.. function:: isfunction(object)
289
Georg Brandl39cadc32010-10-15 16:53:24 +0000290 Return true if the object is a Python function, which includes functions
291 created by a :term:`lambda` expression.
Georg Brandl116aa622007-08-15 14:28:22 +0000292
293
Christian Heimes7131fd92008-02-19 14:21:46 +0000294.. function:: isgeneratorfunction(object)
295
296 Return true if the object is a Python generator function.
297
298
299.. function:: isgenerator(object)
300
301 Return true if the object is a generator.
302
303
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400304.. function:: iscoroutinefunction(object)
305
Yury Selivanov5376ba92015-06-22 12:19:30 -0400306 Return true if the object is a :term:`coroutine function`
307 (a function defined with an :keyword:`async def` syntax).
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400308
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400309 .. versionadded:: 3.5
310
311
312.. function:: iscoroutine(object)
313
Yury Selivanov5376ba92015-06-22 12:19:30 -0400314 Return true if the object is a :term:`coroutine` created by an
315 :keyword:`async def` function.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400316
317 .. versionadded:: 3.5
318
319
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400320.. function:: isawaitable(object)
321
322 Return true if the object can be used in :keyword:`await` expression.
323
324 Can also be used to distinguish generator-based coroutines from regular
325 generators::
326
327 def gen():
328 yield
329 @types.coroutine
330 def gen_coro():
331 yield
332
333 assert not isawaitable(gen())
334 assert isawaitable(gen_coro())
335
336 .. versionadded:: 3.5
337
338
Georg Brandl116aa622007-08-15 14:28:22 +0000339.. function:: istraceback(object)
340
341 Return true if the object is a traceback.
342
343
344.. function:: isframe(object)
345
346 Return true if the object is a frame.
347
348
349.. function:: iscode(object)
350
351 Return true if the object is a code.
352
353
354.. function:: isbuiltin(object)
355
Georg Brandl39cadc32010-10-15 16:53:24 +0000356 Return true if the object is a built-in function or a bound built-in method.
Georg Brandl116aa622007-08-15 14:28:22 +0000357
358
359.. function:: isroutine(object)
360
361 Return true if the object is a user-defined or built-in function or method.
362
Georg Brandl39cadc32010-10-15 16:53:24 +0000363
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000364.. function:: isabstract(object)
365
366 Return true if the object is an abstract base class.
367
Georg Brandl116aa622007-08-15 14:28:22 +0000368
369.. function:: ismethoddescriptor(object)
370
Georg Brandl39cadc32010-10-15 16:53:24 +0000371 Return true if the object is a method descriptor, but not if
372 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
373 are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000374
Georg Brandle6bcc912008-05-12 18:05:20 +0000375 This, for example, is true of ``int.__add__``. An object passing this test
376 has a :attr:`__get__` attribute but not a :attr:`__set__` attribute, but
377 beyond that the set of attributes varies. :attr:`__name__` is usually
378 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000379
Georg Brandl9afde1c2007-11-01 20:32:30 +0000380 Methods implemented via descriptors that also pass one of the other tests
381 return false from the :func:`ismethoddescriptor` test, simply because the
382 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000383 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000384
385
386.. function:: isdatadescriptor(object)
387
388 Return true if the object is a data descriptor.
389
Georg Brandl9afde1c2007-11-01 20:32:30 +0000390 Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute.
391 Examples are properties (defined in Python), getsets, and members. The
392 latter two are defined in C and there are more specific tests available for
393 those types, which is robust across Python implementations. Typically, data
394 descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes
395 (properties, getsets, and members have both of these attributes), but this is
396 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000397
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399.. function:: isgetsetdescriptor(object)
400
401 Return true if the object is a getset descriptor.
402
Georg Brandl495f7b52009-10-27 15:28:25 +0000403 .. impl-detail::
404
405 getsets are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000406 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000407 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000408
Georg Brandl116aa622007-08-15 14:28:22 +0000409
410.. function:: ismemberdescriptor(object)
411
412 Return true if the object is a member descriptor.
413
Georg Brandl495f7b52009-10-27 15:28:25 +0000414 .. impl-detail::
415
416 Member descriptors are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000417 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000418 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000419
Georg Brandl116aa622007-08-15 14:28:22 +0000420
421.. _inspect-source:
422
423Retrieving source code
424----------------------
425
Georg Brandl116aa622007-08-15 14:28:22 +0000426.. function:: getdoc(object)
427
Georg Brandl0c77a822008-06-10 16:37:50 +0000428 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300429 If the documentation string for an object is not provided and the object is
430 a class, a method, a property or a descriptor, retrieve the documentation
431 string from the inheritance hierarchy.
Georg Brandl116aa622007-08-15 14:28:22 +0000432
Berker Peksag4333d8b2015-07-30 18:06:09 +0300433 .. versionchanged:: 3.5
434 Documentation strings are now inherited if not overridden.
435
Georg Brandl116aa622007-08-15 14:28:22 +0000436
437.. function:: getcomments(object)
438
439 Return in a single string any lines of comments immediately preceding the
440 object's source code (for a class, function, or method), or at the top of the
441 Python source file (if the object is a module).
442
443
444.. function:: getfile(object)
445
446 Return the name of the (text or binary) file in which an object was defined.
447 This will fail with a :exc:`TypeError` if the object is a built-in module,
448 class, or function.
449
450
451.. function:: getmodule(object)
452
453 Try to guess which module an object was defined in.
454
455
456.. function:: getsourcefile(object)
457
458 Return the name of the Python source file in which an object was defined. This
459 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
460 function.
461
462
463.. function:: getsourcelines(object)
464
465 Return a list of source lines and starting line number for an object. The
466 argument may be a module, class, method, function, traceback, frame, or code
467 object. The source code is returned as a list of the lines corresponding to the
468 object and the line number indicates where in the original source file the first
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200469 line of code was found. An :exc:`OSError` is raised if the source code cannot
Georg Brandl116aa622007-08-15 14:28:22 +0000470 be retrieved.
471
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200472 .. versionchanged:: 3.3
473 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
474 former.
475
Georg Brandl116aa622007-08-15 14:28:22 +0000476
477.. function:: getsource(object)
478
479 Return the text of the source code for an object. The argument may be a module,
480 class, method, function, traceback, frame, or code object. The source code is
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200481 returned as a single string. An :exc:`OSError` is raised if the source code
Georg Brandl116aa622007-08-15 14:28:22 +0000482 cannot be retrieved.
483
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200484 .. versionchanged:: 3.3
485 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
486 former.
487
Georg Brandl116aa622007-08-15 14:28:22 +0000488
Georg Brandl0c77a822008-06-10 16:37:50 +0000489.. function:: cleandoc(doc)
490
491 Clean up indentation from docstrings that are indented to line up with blocks
Senthil Kumaranebd84e32016-05-29 20:36:58 -0700492 of code.
493
494 All leading whitespace is removed from the first line. Any leading whitespace
495 that can be uniformly removed from the second line onwards is removed. Empty
496 lines at the beginning and end are subsequently removed. Also, all tabs are
497 expanded to spaces.
Georg Brandl0c77a822008-06-10 16:37:50 +0000498
Georg Brandl0c77a822008-06-10 16:37:50 +0000499
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300500.. _inspect-signature-object:
501
Georg Brandle4717722012-08-14 09:45:28 +0200502Introspecting callables with the Signature object
503-------------------------------------------------
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300504
505.. versionadded:: 3.3
506
Georg Brandle4717722012-08-14 09:45:28 +0200507The Signature object represents the call signature of a callable object and its
508return annotation. To retrieve a Signature object, use the :func:`signature`
509function.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300510
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400511.. function:: signature(callable, \*, follow_wrapped=True)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300512
Georg Brandle4717722012-08-14 09:45:28 +0200513 Return a :class:`Signature` object for the given ``callable``::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300514
515 >>> from inspect import signature
516 >>> def foo(a, *, b:int, **kwargs):
517 ... pass
518
519 >>> sig = signature(foo)
520
521 >>> str(sig)
522 '(a, *, b:int, **kwargs)'
523
524 >>> str(sig.parameters['b'])
525 'b:int'
526
527 >>> sig.parameters['b'].annotation
528 <class 'int'>
529
Georg Brandle4717722012-08-14 09:45:28 +0200530 Accepts a wide range of python callables, from plain functions and classes to
531 :func:`functools.partial` objects.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300532
Larry Hastings5c661892014-01-24 06:17:25 -0800533 Raises :exc:`ValueError` if no signature can be provided, and
534 :exc:`TypeError` if that type of object is not supported.
535
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400536 .. versionadded:: 3.5
537 ``follow_wrapped`` parameter. Pass ``False`` to get a signature of
538 ``callable`` specifically (``callable.__wrapped__`` will not be used to
539 unwrap decorated callables.)
540
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300541 .. note::
542
Georg Brandle4717722012-08-14 09:45:28 +0200543 Some callables may not be introspectable in certain implementations of
Yury Selivanovd71e52f2014-01-30 00:22:57 -0500544 Python. For example, in CPython, some built-in functions defined in
545 C provide no metadata about their arguments.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300546
547
Yury Selivanov78356892014-01-30 00:10:54 -0500548.. class:: Signature(parameters=None, \*, return_annotation=Signature.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300549
Georg Brandle4717722012-08-14 09:45:28 +0200550 A Signature object represents the call signature of a function and its return
551 annotation. For each parameter accepted by the function it stores a
552 :class:`Parameter` object in its :attr:`parameters` collection.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300553
Yury Selivanov78356892014-01-30 00:10:54 -0500554 The optional *parameters* argument is a sequence of :class:`Parameter`
555 objects, which is validated to check that there are no parameters with
556 duplicate names, and that the parameters are in the right order, i.e.
557 positional-only first, then positional-or-keyword, and that parameters with
558 defaults follow parameters without defaults.
559
560 The optional *return_annotation* argument, can be an arbitrary Python object,
561 is the "return" annotation of the callable.
562
Georg Brandle4717722012-08-14 09:45:28 +0200563 Signature objects are *immutable*. Use :meth:`Signature.replace` to make a
564 modified copy.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300565
Yury Selivanov67d727e2014-03-29 13:24:14 -0400566 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400567 Signature objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400568
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300569 .. attribute:: Signature.empty
570
571 A special class-level marker to specify absence of a return annotation.
572
573 .. attribute:: Signature.parameters
574
575 An ordered mapping of parameters' names to the corresponding
576 :class:`Parameter` objects.
577
578 .. attribute:: Signature.return_annotation
579
Georg Brandle4717722012-08-14 09:45:28 +0200580 The "return" annotation for the callable. If the callable has no "return"
581 annotation, this attribute is set to :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300582
583 .. method:: Signature.bind(*args, **kwargs)
584
Georg Brandle4717722012-08-14 09:45:28 +0200585 Create a mapping from positional and keyword arguments to parameters.
586 Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
587 signature, or raises a :exc:`TypeError`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300588
589 .. method:: Signature.bind_partial(*args, **kwargs)
590
Georg Brandle4717722012-08-14 09:45:28 +0200591 Works the same way as :meth:`Signature.bind`, but allows the omission of
592 some required arguments (mimics :func:`functools.partial` behavior.)
593 Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
594 passed arguments do not match the signature.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300595
Ezio Melotti8429b672012-09-14 06:35:09 +0300596 .. method:: Signature.replace(*[, parameters][, return_annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300597
Georg Brandle4717722012-08-14 09:45:28 +0200598 Create a new Signature instance based on the instance replace was invoked
599 on. It is possible to pass different ``parameters`` and/or
600 ``return_annotation`` to override the corresponding properties of the base
601 signature. To remove return_annotation from the copied Signature, pass in
602 :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300603
604 ::
605
606 >>> def test(a, b):
607 ... pass
608 >>> sig = signature(test)
609 >>> new_sig = sig.replace(return_annotation="new return anno")
610 >>> str(new_sig)
611 "(a, b) -> 'new return anno'"
612
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400613 .. classmethod:: Signature.from_callable(obj, \*, follow_wrapped=True)
Yury Selivanovda396452014-03-27 12:09:24 -0400614
615 Return a :class:`Signature` (or its subclass) object for a given callable
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400616 ``obj``. Pass ``follow_wrapped=False`` to get a signature of ``obj``
617 without unwrapping its ``__wrapped__`` chain.
Yury Selivanovda396452014-03-27 12:09:24 -0400618
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400619 This method simplifies subclassing of :class:`Signature`::
Yury Selivanovda396452014-03-27 12:09:24 -0400620
621 class MySignature(Signature):
622 pass
623 sig = MySignature.from_callable(min)
624 assert isinstance(sig, MySignature)
625
Yury Selivanov232b9342014-03-29 13:18:30 -0400626 .. versionadded:: 3.5
627
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300628
Yury Selivanov78356892014-01-30 00:10:54 -0500629.. class:: Parameter(name, kind, \*, default=Parameter.empty, annotation=Parameter.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300630
Georg Brandle4717722012-08-14 09:45:28 +0200631 Parameter objects are *immutable*. Instead of modifying a Parameter object,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300632 you can use :meth:`Parameter.replace` to create a modified copy.
633
Yury Selivanov67d727e2014-03-29 13:24:14 -0400634 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400635 Parameter objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400636
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300637 .. attribute:: Parameter.empty
638
Georg Brandle4717722012-08-14 09:45:28 +0200639 A special class-level marker to specify absence of default values and
640 annotations.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300641
642 .. attribute:: Parameter.name
643
Yury Selivanov2393dca2014-01-27 15:07:58 -0500644 The name of the parameter as a string. The name must be a valid
645 Python identifier.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300646
647 .. attribute:: Parameter.default
648
Georg Brandle4717722012-08-14 09:45:28 +0200649 The default value for the parameter. If the parameter has no default
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300650 value, this attribute is set to :attr:`Parameter.empty`.
651
652 .. attribute:: Parameter.annotation
653
Georg Brandle4717722012-08-14 09:45:28 +0200654 The annotation for the parameter. If the parameter has no annotation,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300655 this attribute is set to :attr:`Parameter.empty`.
656
657 .. attribute:: Parameter.kind
658
Georg Brandle4717722012-08-14 09:45:28 +0200659 Describes how argument values are bound to the parameter. Possible values
660 (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300661
Georg Brandl44ea77b2013-03-28 13:28:44 +0100662 .. tabularcolumns:: |l|L|
663
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300664 +------------------------+----------------------------------------------+
665 | Name | Meaning |
666 +========================+==============================================+
667 | *POSITIONAL_ONLY* | Value must be supplied as a positional |
668 | | argument. |
669 | | |
670 | | Python has no explicit syntax for defining |
671 | | positional-only parameters, but many built-in|
672 | | and extension module functions (especially |
673 | | those that accept only one or two parameters)|
674 | | accept them. |
675 +------------------------+----------------------------------------------+
676 | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
677 | | positional argument (this is the standard |
678 | | binding behaviour for functions implemented |
679 | | in Python.) |
680 +------------------------+----------------------------------------------+
681 | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
682 | | bound to any other parameter. This |
683 | | corresponds to a ``*args`` parameter in a |
684 | | Python function definition. |
685 +------------------------+----------------------------------------------+
686 | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
687 | | Keyword only parameters are those which |
688 | | appear after a ``*`` or ``*args`` entry in a |
689 | | Python function definition. |
690 +------------------------+----------------------------------------------+
691 | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
692 | | to any other parameter. This corresponds to a|
693 | | ``**kwargs`` parameter in a Python function |
694 | | definition. |
695 +------------------------+----------------------------------------------+
696
Andrew Svetloveed18082012-08-13 18:23:54 +0300697 Example: print all keyword-only arguments without default values::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300698
699 >>> def foo(a, b, *, c, d=10):
700 ... pass
701
702 >>> sig = signature(foo)
703 >>> for param in sig.parameters.values():
704 ... if (param.kind == param.KEYWORD_ONLY and
705 ... param.default is param.empty):
706 ... print('Parameter:', param)
707 Parameter: c
708
Ezio Melotti8429b672012-09-14 06:35:09 +0300709 .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300710
Georg Brandle4717722012-08-14 09:45:28 +0200711 Create a new Parameter instance based on the instance replaced was invoked
712 on. To override a :class:`Parameter` attribute, pass the corresponding
713 argument. To remove a default value or/and an annotation from a
714 Parameter, pass :attr:`Parameter.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300715
716 ::
717
718 >>> from inspect import Parameter
719 >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
720 >>> str(param)
721 'foo=42'
722
723 >>> str(param.replace()) # Will create a shallow copy of 'param'
724 'foo=42'
725
726 >>> str(param.replace(default=Parameter.empty, annotation='spam'))
727 "foo:'spam'"
728
Yury Selivanov2393dca2014-01-27 15:07:58 -0500729 .. versionchanged:: 3.4
730 In Python 3.3 Parameter objects were allowed to have ``name`` set
731 to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``.
732 This is no longer permitted.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300733
734.. class:: BoundArguments
735
736 Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
737 Holds the mapping of arguments to the function's parameters.
738
739 .. attribute:: BoundArguments.arguments
740
741 An ordered, mutable mapping (:class:`collections.OrderedDict`) of
Georg Brandle4717722012-08-14 09:45:28 +0200742 parameters' names to arguments' values. Contains only explicitly bound
743 arguments. Changes in :attr:`arguments` will reflect in :attr:`args` and
744 :attr:`kwargs`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300745
Georg Brandle4717722012-08-14 09:45:28 +0200746 Should be used in conjunction with :attr:`Signature.parameters` for any
747 argument processing purposes.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300748
749 .. note::
750
751 Arguments for which :meth:`Signature.bind` or
752 :meth:`Signature.bind_partial` relied on a default value are skipped.
Yury Selivanovb907a512015-05-16 13:45:09 -0400753 However, if needed, use :meth:`BoundArguments.apply_defaults` to add
754 them.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300755
756 .. attribute:: BoundArguments.args
757
Georg Brandle4717722012-08-14 09:45:28 +0200758 A tuple of positional arguments values. Dynamically computed from the
759 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300760
761 .. attribute:: BoundArguments.kwargs
762
Georg Brandle4717722012-08-14 09:45:28 +0200763 A dict of keyword arguments values. Dynamically computed from the
764 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300765
Yury Selivanov82796192015-05-14 14:14:02 -0400766 .. attribute:: BoundArguments.signature
767
768 A reference to the parent :class:`Signature` object.
769
Yury Selivanovb907a512015-05-16 13:45:09 -0400770 .. method:: BoundArguments.apply_defaults()
771
772 Set default values for missing arguments.
773
774 For variable-positional arguments (``*args``) the default is an
775 empty tuple.
776
777 For variable-keyword arguments (``**kwargs``) the default is an
778 empty dict.
779
780 ::
781
782 >>> def foo(a, b='ham', *args): pass
783 >>> ba = inspect.signature(foo).bind('spam')
784 >>> ba.apply_defaults()
785 >>> ba.arguments
786 OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])
787
Berker Peksag5b3df5b2015-05-16 23:29:31 +0300788 .. versionadded:: 3.5
789
Georg Brandle4717722012-08-14 09:45:28 +0200790 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
791 functions::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300792
793 def test(a, *, b):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300794 ...
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300795
796 sig = signature(test)
797 ba = sig.bind(10, b=20)
798 test(*ba.args, **ba.kwargs)
799
800
Georg Brandle4717722012-08-14 09:45:28 +0200801.. seealso::
802
803 :pep:`362` - Function Signature Object.
804 The detailed specification, implementation details and examples.
805
806
Georg Brandl116aa622007-08-15 14:28:22 +0000807.. _inspect-classes-functions:
808
809Classes and functions
810---------------------
811
Georg Brandl3dd33882009-06-01 17:35:27 +0000812.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000813
814 Arrange the given list of classes into a hierarchy of nested lists. Where a
815 nested list appears, it contains classes derived from the class whose entry
816 immediately precedes the list. Each entry is a 2-tuple containing a class and a
817 tuple of its base classes. If the *unique* argument is true, exactly one entry
818 appears in the returned structure for each class in the given list. Otherwise,
819 classes using multiple inheritance and their descendants will appear multiple
820 times.
821
822
823.. function:: getargspec(func)
824
Georg Brandl82402752010-01-09 09:48:46 +0000825 Get the names and default values of a Python function's arguments. A
Georg Brandlb30f3302011-01-06 09:23:56 +0000826 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
827 returned. *args* is a list of the argument names. *varargs* and *keywords*
828 are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700829 tuple of default argument values or ``None`` if there are no default
830 arguments; if this tuple has *n* elements, they correspond to the last
831 *n* elements listed in *args*.
Georg Brandl138bcb52007-09-12 19:04:21 +0000832
833 .. deprecated:: 3.0
Yury Selivanov945fff42015-05-22 16:28:05 -0400834 Use :func:`signature` and
835 :ref:`Signature Object <inspect-signature-object>`, which provide a
Yury Selivanova7c159d2016-01-11 21:04:50 -0500836 better introspecting API for callables.
Georg Brandl138bcb52007-09-12 19:04:21 +0000837
838
839.. function:: getfullargspec(func)
840
Georg Brandl82402752010-01-09 09:48:46 +0000841 Get the names and default values of a Python function's arguments. A
842 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000843
Georg Brandl3dd33882009-06-01 17:35:27 +0000844 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
845 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000846
847 *args* is a list of the argument names. *varargs* and *varkw* are the names
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700848 of the ``*`` and ``**`` arguments or ``None``. *defaults* is an *n*-tuple
849 of the default values of the last *n* arguments, or ``None`` if there are no
850 default arguments. *kwonlyargs* is a list of
Georg Brandl138bcb52007-09-12 19:04:21 +0000851 keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
852 from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
853 names to annotations.
854
855 The first four items in the tuple correspond to :func:`getargspec`.
Georg Brandl116aa622007-08-15 14:28:22 +0000856
Nick Coghlan16355782014-03-08 16:36:37 +1000857 .. versionchanged:: 3.4
858 This function is now based on :func:`signature`, but still ignores
859 ``__wrapped__`` attributes and includes the already bound first
860 parameter in the signature output for bound methods.
861
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400862 .. deprecated:: 3.5
863 Use :func:`signature` and
864 :ref:`Signature Object <inspect-signature-object>`, which provide a
865 better introspecting API for callables.
866
Georg Brandl116aa622007-08-15 14:28:22 +0000867
868.. function:: getargvalues(frame)
869
Georg Brandl3dd33882009-06-01 17:35:27 +0000870 Get information about arguments passed into a particular frame. A
871 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000872 returned. *args* is a list of the argument names. *varargs* and *keywords*
873 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000874 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000875
Yury Selivanov945fff42015-05-22 16:28:05 -0400876 .. deprecated:: 3.5
877 Use :func:`signature` and
878 :ref:`Signature Object <inspect-signature-object>`, which provide a
879 better introspecting API for callables.
880
Georg Brandl116aa622007-08-15 14:28:22 +0000881
Andrew Svetlov735d3172012-10-27 00:28:20 +0300882.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Georg Brandl116aa622007-08-15 14:28:22 +0000883
Michael Foord3af125a2012-04-21 18:22:28 +0100884 Format a pretty argument spec from the values returned by
885 :func:`getargspec` or :func:`getfullargspec`.
886
887 The first seven arguments are (``args``, ``varargs``, ``varkw``,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100888 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
Andrew Svetlov735d3172012-10-27 00:28:20 +0300889
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100890 The other six arguments are functions that are called to turn argument names,
891 ``*`` argument name, ``**`` argument name, default values, return annotation
892 and individual annotations into strings, respectively.
893
894 For example:
895
896 >>> from inspect import formatargspec, getfullargspec
897 >>> def f(a: int, b: float):
898 ... pass
899 ...
900 >>> formatargspec(*getfullargspec(f))
901 '(a: int, b: float)'
Georg Brandl116aa622007-08-15 14:28:22 +0000902
Yury Selivanov945fff42015-05-22 16:28:05 -0400903 .. deprecated:: 3.5
904 Use :func:`signature` and
905 :ref:`Signature Object <inspect-signature-object>`, which provide a
906 better introspecting API for callables.
907
Georg Brandl116aa622007-08-15 14:28:22 +0000908
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000909.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000910
911 Format a pretty argument spec from the four values returned by
912 :func:`getargvalues`. The format\* arguments are the corresponding optional
913 formatting functions that are called to turn names and values into strings.
914
Yury Selivanov945fff42015-05-22 16:28:05 -0400915 .. deprecated:: 3.5
916 Use :func:`signature` and
917 :ref:`Signature Object <inspect-signature-object>`, which provide a
918 better introspecting API for callables.
919
Georg Brandl116aa622007-08-15 14:28:22 +0000920
921.. function:: getmro(cls)
922
923 Return a tuple of class cls's base classes, including cls, in method resolution
924 order. No class appears more than once in this tuple. Note that the method
925 resolution order depends on cls's type. Unless a very peculiar user-defined
926 metatype is in use, cls will be the first element of the tuple.
927
928
Benjamin Peterson3a990c62014-01-02 12:22:30 -0600929.. function:: getcallargs(func, *args, **kwds)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000930
931 Bind the *args* and *kwds* to the argument names of the Python function or
932 method *func*, as if it was called with them. For bound methods, bind also the
933 first argument (typically named ``self``) to the associated instance. A dict
934 is returned, mapping the argument names (including the names of the ``*`` and
935 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
936 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
937 an exception because of incompatible signature, an exception of the same type
938 and the same or similar message is raised. For example::
939
940 >>> from inspect import getcallargs
941 >>> def f(a, b=1, *pos, **named):
942 ... pass
Andrew Svetlove939f382012-08-09 13:25:32 +0300943 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
944 True
945 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
946 True
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000947 >>> getcallargs(f)
948 Traceback (most recent call last):
949 ...
Andrew Svetlove939f382012-08-09 13:25:32 +0300950 TypeError: f() missing 1 required positional argument: 'a'
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000951
952 .. versionadded:: 3.2
953
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400954 .. deprecated:: 3.5
955 Use :meth:`Signature.bind` and :meth:`Signature.bind_partial` instead.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300956
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000957
Nick Coghlan2f92e542012-06-23 19:39:55 +1000958.. function:: getclosurevars(func)
959
960 Get the mapping of external name references in a Python function or
961 method *func* to their current values. A
962 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
963 is returned. *nonlocals* maps referenced names to lexical closure
964 variables, *globals* to the function's module globals and *builtins* to
965 the builtins visible from the function body. *unbound* is the set of names
966 referenced in the function that could not be resolved at all given the
967 current module globals and builtins.
968
969 :exc:`TypeError` is raised if *func* is not a Python function or method.
970
971 .. versionadded:: 3.3
972
973
Nick Coghlane8c45d62013-07-28 20:00:01 +1000974.. function:: unwrap(func, *, stop=None)
975
976 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
977 attributes returning the last object in the chain.
978
979 *stop* is an optional callback accepting an object in the wrapper chain
980 as its sole argument that allows the unwrapping to be terminated early if
981 the callback returns a true value. If the callback never returns a true
982 value, the last object in the chain is returned as usual. For example,
983 :func:`signature` uses this to stop unwrapping if any object in the
984 chain has a ``__signature__`` attribute defined.
985
986 :exc:`ValueError` is raised if a cycle is encountered.
987
988 .. versionadded:: 3.4
989
990
Georg Brandl116aa622007-08-15 14:28:22 +0000991.. _inspect-stack:
992
993The interpreter stack
994---------------------
995
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400996When the following functions return "frame records," each record is a
997:term:`named tuple`
998``FrameInfo(frame, filename, lineno, function, code_context, index)``.
999The tuple contains the frame object, the filename, the line number of the
1000current line,
Georg Brandl116aa622007-08-15 14:28:22 +00001001the function name, a list of lines of context from the source code, and the
1002index of the current line within that list.
1003
Antoine Pitroucdcafb72014-08-24 10:50:28 -04001004.. versionchanged:: 3.5
1005 Return a named tuple instead of a tuple.
1006
Georg Brandle720c0a2009-04-27 16:20:50 +00001007.. note::
Georg Brandl116aa622007-08-15 14:28:22 +00001008
1009 Keeping references to frame objects, as found in the first element of the frame
1010 records these functions return, can cause your program to create reference
1011 cycles. Once a reference cycle has been created, the lifespan of all objects
1012 which can be accessed from the objects which form the cycle can become much
1013 longer even if Python's optional cycle detector is enabled. If such cycles must
1014 be created, it is important to ensure they are explicitly broken to avoid the
1015 delayed destruction of objects and increased memory consumption which occurs.
1016
1017 Though the cycle detector will catch these, destruction of the frames (and local
1018 variables) can be made deterministic by removing the cycle in a
1019 :keyword:`finally` clause. This is also important if the cycle detector was
1020 disabled when Python was compiled or using :func:`gc.disable`. For example::
1021
1022 def handle_stackframe_without_leak():
1023 frame = inspect.currentframe()
1024 try:
1025 # do something with the frame
1026 finally:
1027 del frame
1028
Antoine Pitrou58720d62013-08-05 23:26:40 +02001029 If you want to keep the frame around (for example to print a traceback
1030 later), you can also break reference cycles by using the
1031 :meth:`frame.clear` method.
1032
Georg Brandl116aa622007-08-15 14:28:22 +00001033The optional *context* argument supported by most of these functions specifies
1034the number of lines of context to return, which are centered around the current
1035line.
1036
1037
Georg Brandl3dd33882009-06-01 17:35:27 +00001038.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001039
Georg Brandl48310cd2009-01-03 21:18:54 +00001040 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +00001041 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +00001042
1043
Georg Brandl3dd33882009-06-01 17:35:27 +00001044.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001045
1046 Get a list of frame records for a frame and all outer frames. These frames
1047 represent the calls that lead to the creation of *frame*. The first entry in the
1048 returned list represents *frame*; the last entry represents the outermost call
1049 on *frame*'s stack.
1050
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001051 .. versionchanged:: 3.5
1052 A list of :term:`named tuples <named tuple>`
1053 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1054 is returned.
1055
Georg Brandl116aa622007-08-15 14:28:22 +00001056
Georg Brandl3dd33882009-06-01 17:35:27 +00001057.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001058
1059 Get a list of frame records for a traceback's frame and all inner frames. These
1060 frames represent calls made as a consequence of *frame*. The first entry in the
1061 list represents *traceback*; the last entry represents where the exception was
1062 raised.
1063
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001064 .. versionchanged:: 3.5
1065 A list of :term:`named tuples <named tuple>`
1066 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1067 is returned.
1068
Georg Brandl116aa622007-08-15 14:28:22 +00001069
1070.. function:: currentframe()
1071
1072 Return the frame object for the caller's stack frame.
1073
Georg Brandl495f7b52009-10-27 15:28:25 +00001074 .. impl-detail::
1075
1076 This function relies on Python stack frame support in the interpreter,
1077 which isn't guaranteed to exist in all implementations of Python. If
1078 running in an implementation without Python stack frame support this
1079 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001080
Georg Brandl116aa622007-08-15 14:28:22 +00001081
Georg Brandl3dd33882009-06-01 17:35:27 +00001082.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001083
1084 Return a list of frame records for the caller's stack. The first entry in the
1085 returned list represents the caller; the last entry represents the outermost
1086 call on the stack.
1087
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001088 .. versionchanged:: 3.5
1089 A list of :term:`named tuples <named tuple>`
1090 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1091 is returned.
1092
Georg Brandl116aa622007-08-15 14:28:22 +00001093
Georg Brandl3dd33882009-06-01 17:35:27 +00001094.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001095
1096 Return a list of frame records for the stack between the current frame and the
1097 frame in which an exception currently being handled was raised in. The first
1098 entry in the list represents the caller; the last entry represents where the
1099 exception was raised.
1100
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001101 .. versionchanged:: 3.5
1102 A list of :term:`named tuples <named tuple>`
1103 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1104 is returned.
1105
Michael Foord95fc51d2010-11-20 15:07:30 +00001106
1107Fetching attributes statically
1108------------------------------
1109
1110Both :func:`getattr` and :func:`hasattr` can trigger code execution when
1111fetching or checking for the existence of attributes. Descriptors, like
1112properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
1113may be called.
1114
1115For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +02001116can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +00001117but avoids executing code when it fetches attributes.
1118
1119.. function:: getattr_static(obj, attr, default=None)
1120
1121 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +02001122 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +00001123
1124 Note: this function may not be able to retrieve all attributes
1125 that getattr can fetch (like dynamically created attributes)
1126 and may find attributes that getattr can't (like descriptors
1127 that raise AttributeError). It can also return descriptors objects
1128 instead of instance members.
1129
Serhiy Storchakabfdcd432013-10-13 23:09:14 +03001130 If the instance :attr:`~object.__dict__` is shadowed by another member (for
1131 example a property) then this function will be unable to find instance
1132 members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001133
Michael Foorddcebe0f2011-03-15 19:20:44 -04001134 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +00001135
Éric Araujo941afed2011-09-01 02:47:34 +02001136:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +00001137getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +00001138is returned instead of the underlying attribute.
1139
1140You can handle these with code like the following. Note that
1141for arbitrary getset descriptors invoking these may trigger
1142code execution::
1143
1144 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +00001145 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +00001146 __slots__ = ['foo']
1147
1148 slot_descriptor = type(_foo.foo)
1149 getset_descriptor = type(type(open(__file__)).name)
1150 wrapper_descriptor = type(str.__dict__['__add__'])
1151 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
1152
1153 result = getattr_static(some_object, 'foo')
1154 if type(result) in descriptor_types:
1155 try:
1156 result = result.__get__()
1157 except AttributeError:
1158 # descriptors can raise AttributeError to
1159 # indicate there is no underlying value
1160 # in which case the descriptor itself will
1161 # have to do
1162 pass
Nick Coghlane0f04652010-11-21 03:44:04 +00001163
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001164
Yury Selivanov5376ba92015-06-22 12:19:30 -04001165Current State of Generators and Coroutines
1166------------------------------------------
Nick Coghlane0f04652010-11-21 03:44:04 +00001167
1168When implementing coroutine schedulers and for other advanced uses of
1169generators, it is useful to determine whether a generator is currently
1170executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001171terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +00001172generator to be determined easily.
1173
1174.. function:: getgeneratorstate(generator)
1175
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001176 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +00001177
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001178 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +00001179 * GEN_CREATED: Waiting to start execution.
1180 * GEN_RUNNING: Currently being executed by the interpreter.
1181 * GEN_SUSPENDED: Currently suspended at a yield expression.
1182 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +00001183
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001184 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001185
Yury Selivanov5376ba92015-06-22 12:19:30 -04001186.. function:: getcoroutinestate(coroutine)
1187
1188 Get current state of a coroutine object. The function is intended to be
1189 used with coroutine objects created by :keyword:`async def` functions, but
1190 will accept any coroutine-like object that has ``cr_running`` and
1191 ``cr_frame`` attributes.
1192
1193 Possible states are:
1194 * CORO_CREATED: Waiting to start execution.
1195 * CORO_RUNNING: Currently being executed by the interpreter.
1196 * CORO_SUSPENDED: Currently suspended at an await expression.
1197 * CORO_CLOSED: Execution has completed.
1198
1199 .. versionadded:: 3.5
1200
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001201The current internal state of the generator can also be queried. This is
1202mostly useful for testing purposes, to ensure that internal state is being
1203updated as expected:
1204
1205.. function:: getgeneratorlocals(generator)
1206
1207 Get the mapping of live local variables in *generator* to their current
1208 values. A dictionary is returned that maps from variable names to values.
1209 This is the equivalent of calling :func:`locals` in the body of the
1210 generator, and all the same caveats apply.
1211
1212 If *generator* is a :term:`generator` with no currently associated frame,
1213 then an empty dictionary is returned. :exc:`TypeError` is raised if
1214 *generator* is not a Python generator object.
1215
1216 .. impl-detail::
1217
1218 This function relies on the generator exposing a Python stack frame
1219 for introspection, which isn't guaranteed to be the case in all
1220 implementations of Python. In such cases, this function will always
1221 return an empty dictionary.
1222
1223 .. versionadded:: 3.3
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001224
Yury Selivanov5376ba92015-06-22 12:19:30 -04001225.. function:: getcoroutinelocals(coroutine)
1226
1227 This function is analogous to :func:`~inspect.getgeneratorlocals`, but
1228 works for coroutine objects created by :keyword:`async def` functions.
1229
1230 .. versionadded:: 3.5
1231
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001232
Nick Coghlan367df122013-10-27 01:57:34 +10001233.. _inspect-module-cli:
1234
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001235Command Line Interface
1236----------------------
1237
1238The :mod:`inspect` module also provides a basic introspection capability
1239from the command line.
1240
1241.. program:: inspect
1242
1243By default, accepts the name of a module and prints the source of that
1244module. A class or function within the module can be printed instead by
1245appended a colon and the qualified name of the target object.
1246
1247.. cmdoption:: --details
1248
1249 Print information about the specified object rather than the source code