blob: d2247e844fa051b668ee9fc545259a4849c04650 [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+-----------+-----------------+---------------------------+
91| traceback | tb_frame | frame object at this |
92| | | level |
93+-----------+-----------------+---------------------------+
94| | tb_lasti | index of last attempted |
95| | | instruction in bytecode |
96+-----------+-----------------+---------------------------+
97| | tb_lineno | current line number in |
98| | | Python source code |
99+-----------+-----------------+---------------------------+
100| | tb_next | next inner traceback |
101| | | object (called by this |
102| | | level) |
103+-----------+-----------------+---------------------------+
104| frame | f_back | next outer frame object |
105| | | (this frame's caller) |
106+-----------+-----------------+---------------------------+
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000107| | f_builtins | builtins namespace seen |
Georg Brandl55ac8f02007-09-01 13:51:09 +0000108| | | by this frame |
109+-----------+-----------------+---------------------------+
110| | f_code | code object being |
111| | | executed in this frame |
112+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000113| | f_globals | global namespace seen by |
114| | | this frame |
115+-----------+-----------------+---------------------------+
116| | f_lasti | index of last attempted |
117| | | instruction in bytecode |
118+-----------+-----------------+---------------------------+
119| | f_lineno | current line number in |
120| | | Python source code |
121+-----------+-----------------+---------------------------+
122| | f_locals | local namespace seen by |
123| | | this frame |
124+-----------+-----------------+---------------------------+
125| | f_restricted | 0 or 1 if frame is in |
126| | | restricted execution mode |
127+-----------+-----------------+---------------------------+
128| | f_trace | tracing function for this |
129| | | frame, or ``None`` |
130+-----------+-----------------+---------------------------+
131| code | co_argcount | number of arguments (not |
132| | | including \* or \*\* |
133| | | args) |
134+-----------+-----------------+---------------------------+
135| | co_code | string of raw compiled |
136| | | bytecode |
137+-----------+-----------------+---------------------------+
138| | co_consts | tuple of constants used |
139| | | in the bytecode |
140+-----------+-----------------+---------------------------+
141| | co_filename | name of file in which |
142| | | this code object was |
143| | | created |
144+-----------+-----------------+---------------------------+
145| | co_firstlineno | number of first line in |
146| | | Python source code |
147+-----------+-----------------+---------------------------+
148| | co_flags | bitmap: 1=optimized ``|`` |
149| | | 2=newlocals ``|`` 4=\*arg |
150| | | ``|`` 8=\*\*arg |
151+-----------+-----------------+---------------------------+
152| | co_lnotab | encoded mapping of line |
153| | | numbers to bytecode |
154| | | indices |
155+-----------+-----------------+---------------------------+
156| | co_name | name with which this code |
157| | | object was defined |
158+-----------+-----------------+---------------------------+
159| | co_names | tuple of names of local |
160| | | variables |
161+-----------+-----------------+---------------------------+
162| | co_nlocals | number of local variables |
163+-----------+-----------------+---------------------------+
164| | co_stacksize | virtual machine stack |
165| | | space required |
166+-----------+-----------------+---------------------------+
167| | co_varnames | tuple of names of |
168| | | arguments and local |
169| | | variables |
170+-----------+-----------------+---------------------------+
Victor Stinner40ee3012014-06-16 15:59:28 +0200171| generator | __name__ | name |
172+-----------+-----------------+---------------------------+
173| | __qualname__ | qualified name |
174+-----------+-----------------+---------------------------+
175| | gi_frame | frame |
176+-----------+-----------------+---------------------------+
177| | gi_running | is the generator running? |
178+-----------+-----------------+---------------------------+
179| | gi_code | code |
180+-----------+-----------------+---------------------------+
Yury Selivanovc135f0a2015-08-17 13:02:42 -0400181| | gi_yieldfrom | object being iterated by |
182| | | ``yield from``, or |
183| | | ``None`` |
184+-----------+-----------------+---------------------------+
Yury Selivanov5376ba92015-06-22 12:19:30 -0400185| coroutine | __name__ | name |
186+-----------+-----------------+---------------------------+
187| | __qualname__ | qualified name |
188+-----------+-----------------+---------------------------+
Yury Selivanove13f8f32015-07-03 00:23:30 -0400189| | cr_await | object being awaited on, |
190| | | or ``None`` |
191+-----------+-----------------+---------------------------+
Yury Selivanov5376ba92015-06-22 12:19:30 -0400192| | cr_frame | frame |
193+-----------+-----------------+---------------------------+
194| | cr_running | is the coroutine running? |
195+-----------+-----------------+---------------------------+
196| | cr_code | code |
197+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000198| builtin | __doc__ | documentation string |
199+-----------+-----------------+---------------------------+
200| | __name__ | original name of this |
201| | | function or method |
202+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -0400203| | __qualname__ | qualified name |
204+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000205| | __self__ | instance to which a |
206| | | method is bound, or |
207| | | ``None`` |
208+-----------+-----------------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000209
Victor Stinner40ee3012014-06-16 15:59:28 +0200210.. versionchanged:: 3.5
211
Yury Selivanov5fbad3c2015-08-17 13:04:41 -0400212 Add ``__qualname__`` and ``gi_yieldfrom`` attributes to generators.
213
214 The ``__name__`` attribute of generators is now set from the function
215 name, instead of the code name, and it can now be modified.
Victor Stinner40ee3012014-06-16 15:59:28 +0200216
Georg Brandl116aa622007-08-15 14:28:22 +0000217
218.. function:: getmembers(object[, predicate])
219
220 Return all the members of an object in a list of (name, value) pairs sorted by
221 name. If the optional *predicate* argument is supplied, only members for which
222 the predicate returns a true value are included.
223
Christian Heimes7f044312008-01-06 17:05:40 +0000224 .. note::
225
Ethan Furman63c141c2013-10-18 00:27:39 -0700226 :func:`getmembers` will only return class attributes defined in the
227 metaclass when the argument is a class and those attributes have been
228 listed in the metaclass' custom :meth:`__dir__`.
Christian Heimes7f044312008-01-06 17:05:40 +0000229
Georg Brandl116aa622007-08-15 14:28:22 +0000230
231.. function:: getmoduleinfo(path)
232
Georg Brandlb30f3302011-01-06 09:23:56 +0000233 Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode, module_type)``
234 of values that describe how Python will interpret the file identified by
235 *path* if it is a module, or ``None`` if it would not be identified as a
236 module. In that tuple, *name* is the name of the module without the name of
237 any enclosing package, *suffix* is the trailing part of the file name (which
238 may not be a dot-delimited extension), *mode* is the :func:`open` mode that
239 would be used (``'r'`` or ``'rb'``), and *module_type* is an integer giving
240 the type of the module. *module_type* will have a value which can be
241 compared to the constants defined in the :mod:`imp` module; see the
242 documentation for that module for more information on module types.
Georg Brandl116aa622007-08-15 14:28:22 +0000243
Brett Cannoncb66eb02012-05-11 12:58:42 -0400244 .. deprecated:: 3.3
245 You may check the file path's suffix against the supported suffixes
246 listed in :mod:`importlib.machinery` to infer the same information.
247
Georg Brandl116aa622007-08-15 14:28:22 +0000248
249.. function:: getmodulename(path)
250
251 Return the name of the module named by the file *path*, without including the
Nick Coghlan76e07702012-07-18 23:14:57 +1000252 names of enclosing packages. The file extension is checked against all of
253 the entries in :func:`importlib.machinery.all_suffixes`. If it matches,
254 the final path component is returned with the extension removed.
255 Otherwise, ``None`` is returned.
256
257 Note that this function *only* returns a meaningful name for actual
258 Python modules - paths that potentially refer to Python packages will
259 still return ``None``.
260
261 .. versionchanged:: 3.3
262 This function is now based directly on :mod:`importlib` rather than the
263 deprecated :func:`getmoduleinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000264
265
266.. function:: ismodule(object)
267
268 Return true if the object is a module.
269
270
271.. function:: isclass(object)
272
Georg Brandl39cadc32010-10-15 16:53:24 +0000273 Return true if the object is a class, whether built-in or created in Python
274 code.
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276
277.. function:: ismethod(object)
278
Georg Brandl39cadc32010-10-15 16:53:24 +0000279 Return true if the object is a bound method written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000280
281
282.. function:: isfunction(object)
283
Georg Brandl39cadc32010-10-15 16:53:24 +0000284 Return true if the object is a Python function, which includes functions
285 created by a :term:`lambda` expression.
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287
Christian Heimes7131fd92008-02-19 14:21:46 +0000288.. function:: isgeneratorfunction(object)
289
290 Return true if the object is a Python generator function.
291
292
293.. function:: isgenerator(object)
294
295 Return true if the object is a generator.
296
297
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400298.. function:: iscoroutinefunction(object)
299
Yury Selivanov5376ba92015-06-22 12:19:30 -0400300 Return true if the object is a :term:`coroutine function`
301 (a function defined with an :keyword:`async def` syntax).
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400302
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400303 .. versionadded:: 3.5
304
305
306.. function:: iscoroutine(object)
307
Yury Selivanov5376ba92015-06-22 12:19:30 -0400308 Return true if the object is a :term:`coroutine` created by an
309 :keyword:`async def` function.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400310
311 .. versionadded:: 3.5
312
313
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400314.. function:: isawaitable(object)
315
316 Return true if the object can be used in :keyword:`await` expression.
317
318 Can also be used to distinguish generator-based coroutines from regular
319 generators::
320
321 def gen():
322 yield
323 @types.coroutine
324 def gen_coro():
325 yield
326
327 assert not isawaitable(gen())
328 assert isawaitable(gen_coro())
329
330 .. versionadded:: 3.5
331
332
Georg Brandl116aa622007-08-15 14:28:22 +0000333.. function:: istraceback(object)
334
335 Return true if the object is a traceback.
336
337
338.. function:: isframe(object)
339
340 Return true if the object is a frame.
341
342
343.. function:: iscode(object)
344
345 Return true if the object is a code.
346
347
348.. function:: isbuiltin(object)
349
Georg Brandl39cadc32010-10-15 16:53:24 +0000350 Return true if the object is a built-in function or a bound built-in method.
Georg Brandl116aa622007-08-15 14:28:22 +0000351
352
353.. function:: isroutine(object)
354
355 Return true if the object is a user-defined or built-in function or method.
356
Georg Brandl39cadc32010-10-15 16:53:24 +0000357
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000358.. function:: isabstract(object)
359
360 Return true if the object is an abstract base class.
361
Georg Brandl116aa622007-08-15 14:28:22 +0000362
363.. function:: ismethoddescriptor(object)
364
Georg Brandl39cadc32010-10-15 16:53:24 +0000365 Return true if the object is a method descriptor, but not if
366 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
367 are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000368
Georg Brandle6bcc912008-05-12 18:05:20 +0000369 This, for example, is true of ``int.__add__``. An object passing this test
370 has a :attr:`__get__` attribute but not a :attr:`__set__` attribute, but
371 beyond that the set of attributes varies. :attr:`__name__` is usually
372 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000373
Georg Brandl9afde1c2007-11-01 20:32:30 +0000374 Methods implemented via descriptors that also pass one of the other tests
375 return false from the :func:`ismethoddescriptor` test, simply because the
376 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000377 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000378
379
380.. function:: isdatadescriptor(object)
381
382 Return true if the object is a data descriptor.
383
Georg Brandl9afde1c2007-11-01 20:32:30 +0000384 Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute.
385 Examples are properties (defined in Python), getsets, and members. The
386 latter two are defined in C and there are more specific tests available for
387 those types, which is robust across Python implementations. Typically, data
388 descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes
389 (properties, getsets, and members have both of these attributes), but this is
390 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000391
Georg Brandl116aa622007-08-15 14:28:22 +0000392
393.. function:: isgetsetdescriptor(object)
394
395 Return true if the object is a getset descriptor.
396
Georg Brandl495f7b52009-10-27 15:28:25 +0000397 .. impl-detail::
398
399 getsets are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000400 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000401 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000402
Georg Brandl116aa622007-08-15 14:28:22 +0000403
404.. function:: ismemberdescriptor(object)
405
406 Return true if the object is a member descriptor.
407
Georg Brandl495f7b52009-10-27 15:28:25 +0000408 .. impl-detail::
409
410 Member descriptors are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000411 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000412 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000413
Georg Brandl116aa622007-08-15 14:28:22 +0000414
415.. _inspect-source:
416
417Retrieving source code
418----------------------
419
Georg Brandl116aa622007-08-15 14:28:22 +0000420.. function:: getdoc(object)
421
Georg Brandl0c77a822008-06-10 16:37:50 +0000422 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300423 If the documentation string for an object is not provided and the object is
424 a class, a method, a property or a descriptor, retrieve the documentation
425 string from the inheritance hierarchy.
Georg Brandl116aa622007-08-15 14:28:22 +0000426
Berker Peksag4333d8b2015-07-30 18:06:09 +0300427 .. versionchanged:: 3.5
428 Documentation strings are now inherited if not overridden.
429
Georg Brandl116aa622007-08-15 14:28:22 +0000430
431.. function:: getcomments(object)
432
433 Return in a single string any lines of comments immediately preceding the
434 object's source code (for a class, function, or method), or at the top of the
435 Python source file (if the object is a module).
436
437
438.. function:: getfile(object)
439
440 Return the name of the (text or binary) file in which an object was defined.
441 This will fail with a :exc:`TypeError` if the object is a built-in module,
442 class, or function.
443
444
445.. function:: getmodule(object)
446
447 Try to guess which module an object was defined in.
448
449
450.. function:: getsourcefile(object)
451
452 Return the name of the Python source file in which an object was defined. This
453 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
454 function.
455
456
457.. function:: getsourcelines(object)
458
459 Return a list of source lines and starting line number for an object. The
460 argument may be a module, class, method, function, traceback, frame, or code
461 object. The source code is returned as a list of the lines corresponding to the
462 object and the line number indicates where in the original source file the first
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200463 line of code was found. An :exc:`OSError` is raised if the source code cannot
Georg Brandl116aa622007-08-15 14:28:22 +0000464 be retrieved.
465
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200466 .. versionchanged:: 3.3
467 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
468 former.
469
Georg Brandl116aa622007-08-15 14:28:22 +0000470
471.. function:: getsource(object)
472
473 Return the text of the source code for an object. The argument may be a module,
474 class, method, function, traceback, frame, or code object. The source code is
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200475 returned as a single string. An :exc:`OSError` is raised if the source code
Georg Brandl116aa622007-08-15 14:28:22 +0000476 cannot be retrieved.
477
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200478 .. versionchanged:: 3.3
479 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
480 former.
481
Georg Brandl116aa622007-08-15 14:28:22 +0000482
Georg Brandl0c77a822008-06-10 16:37:50 +0000483.. function:: cleandoc(doc)
484
485 Clean up indentation from docstrings that are indented to line up with blocks
486 of code. Any whitespace that can be uniformly removed from the second line
487 onwards is removed. Also, all tabs are expanded to spaces.
488
Georg Brandl0c77a822008-06-10 16:37:50 +0000489
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300490.. _inspect-signature-object:
491
Georg Brandle4717722012-08-14 09:45:28 +0200492Introspecting callables with the Signature object
493-------------------------------------------------
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300494
495.. versionadded:: 3.3
496
Georg Brandle4717722012-08-14 09:45:28 +0200497The Signature object represents the call signature of a callable object and its
498return annotation. To retrieve a Signature object, use the :func:`signature`
499function.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300500
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400501.. function:: signature(callable, \*, follow_wrapped=True)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300502
Georg Brandle4717722012-08-14 09:45:28 +0200503 Return a :class:`Signature` object for the given ``callable``::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300504
505 >>> from inspect import signature
506 >>> def foo(a, *, b:int, **kwargs):
507 ... pass
508
509 >>> sig = signature(foo)
510
511 >>> str(sig)
512 '(a, *, b:int, **kwargs)'
513
514 >>> str(sig.parameters['b'])
515 'b:int'
516
517 >>> sig.parameters['b'].annotation
518 <class 'int'>
519
Georg Brandle4717722012-08-14 09:45:28 +0200520 Accepts a wide range of python callables, from plain functions and classes to
521 :func:`functools.partial` objects.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300522
Larry Hastings5c661892014-01-24 06:17:25 -0800523 Raises :exc:`ValueError` if no signature can be provided, and
524 :exc:`TypeError` if that type of object is not supported.
525
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400526 .. versionadded:: 3.5
527 ``follow_wrapped`` parameter. Pass ``False`` to get a signature of
528 ``callable`` specifically (``callable.__wrapped__`` will not be used to
529 unwrap decorated callables.)
530
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300531 .. note::
532
Georg Brandle4717722012-08-14 09:45:28 +0200533 Some callables may not be introspectable in certain implementations of
Yury Selivanovd71e52f2014-01-30 00:22:57 -0500534 Python. For example, in CPython, some built-in functions defined in
535 C provide no metadata about their arguments.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300536
537
Yury Selivanov78356892014-01-30 00:10:54 -0500538.. class:: Signature(parameters=None, \*, return_annotation=Signature.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300539
Georg Brandle4717722012-08-14 09:45:28 +0200540 A Signature object represents the call signature of a function and its return
541 annotation. For each parameter accepted by the function it stores a
542 :class:`Parameter` object in its :attr:`parameters` collection.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300543
Yury Selivanov78356892014-01-30 00:10:54 -0500544 The optional *parameters* argument is a sequence of :class:`Parameter`
545 objects, which is validated to check that there are no parameters with
546 duplicate names, and that the parameters are in the right order, i.e.
547 positional-only first, then positional-or-keyword, and that parameters with
548 defaults follow parameters without defaults.
549
550 The optional *return_annotation* argument, can be an arbitrary Python object,
551 is the "return" annotation of the callable.
552
Georg Brandle4717722012-08-14 09:45:28 +0200553 Signature objects are *immutable*. Use :meth:`Signature.replace` to make a
554 modified copy.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300555
Yury Selivanov67d727e2014-03-29 13:24:14 -0400556 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400557 Signature objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400558
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300559 .. attribute:: Signature.empty
560
561 A special class-level marker to specify absence of a return annotation.
562
563 .. attribute:: Signature.parameters
564
565 An ordered mapping of parameters' names to the corresponding
566 :class:`Parameter` objects.
567
568 .. attribute:: Signature.return_annotation
569
Georg Brandle4717722012-08-14 09:45:28 +0200570 The "return" annotation for the callable. If the callable has no "return"
571 annotation, this attribute is set to :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300572
573 .. method:: Signature.bind(*args, **kwargs)
574
Georg Brandle4717722012-08-14 09:45:28 +0200575 Create a mapping from positional and keyword arguments to parameters.
576 Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
577 signature, or raises a :exc:`TypeError`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300578
579 .. method:: Signature.bind_partial(*args, **kwargs)
580
Georg Brandle4717722012-08-14 09:45:28 +0200581 Works the same way as :meth:`Signature.bind`, but allows the omission of
582 some required arguments (mimics :func:`functools.partial` behavior.)
583 Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
584 passed arguments do not match the signature.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300585
Ezio Melotti8429b672012-09-14 06:35:09 +0300586 .. method:: Signature.replace(*[, parameters][, return_annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300587
Georg Brandle4717722012-08-14 09:45:28 +0200588 Create a new Signature instance based on the instance replace was invoked
589 on. It is possible to pass different ``parameters`` and/or
590 ``return_annotation`` to override the corresponding properties of the base
591 signature. To remove return_annotation from the copied Signature, pass in
592 :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300593
594 ::
595
596 >>> def test(a, b):
597 ... pass
598 >>> sig = signature(test)
599 >>> new_sig = sig.replace(return_annotation="new return anno")
600 >>> str(new_sig)
601 "(a, b) -> 'new return anno'"
602
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400603 .. classmethod:: Signature.from_callable(obj, \*, follow_wrapped=True)
Yury Selivanovda396452014-03-27 12:09:24 -0400604
605 Return a :class:`Signature` (or its subclass) object for a given callable
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400606 ``obj``. Pass ``follow_wrapped=False`` to get a signature of ``obj``
607 without unwrapping its ``__wrapped__`` chain.
Yury Selivanovda396452014-03-27 12:09:24 -0400608
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400609 This method simplifies subclassing of :class:`Signature`::
Yury Selivanovda396452014-03-27 12:09:24 -0400610
611 class MySignature(Signature):
612 pass
613 sig = MySignature.from_callable(min)
614 assert isinstance(sig, MySignature)
615
Yury Selivanov232b9342014-03-29 13:18:30 -0400616 .. versionadded:: 3.5
617
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300618
Yury Selivanov78356892014-01-30 00:10:54 -0500619.. class:: Parameter(name, kind, \*, default=Parameter.empty, annotation=Parameter.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300620
Georg Brandle4717722012-08-14 09:45:28 +0200621 Parameter objects are *immutable*. Instead of modifying a Parameter object,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300622 you can use :meth:`Parameter.replace` to create a modified copy.
623
Yury Selivanov67d727e2014-03-29 13:24:14 -0400624 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400625 Parameter objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400626
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300627 .. attribute:: Parameter.empty
628
Georg Brandle4717722012-08-14 09:45:28 +0200629 A special class-level marker to specify absence of default values and
630 annotations.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300631
632 .. attribute:: Parameter.name
633
Yury Selivanov2393dca2014-01-27 15:07:58 -0500634 The name of the parameter as a string. The name must be a valid
635 Python identifier.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300636
637 .. attribute:: Parameter.default
638
Georg Brandle4717722012-08-14 09:45:28 +0200639 The default value for the parameter. If the parameter has no default
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300640 value, this attribute is set to :attr:`Parameter.empty`.
641
642 .. attribute:: Parameter.annotation
643
Georg Brandle4717722012-08-14 09:45:28 +0200644 The annotation for the parameter. If the parameter has no annotation,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300645 this attribute is set to :attr:`Parameter.empty`.
646
647 .. attribute:: Parameter.kind
648
Georg Brandle4717722012-08-14 09:45:28 +0200649 Describes how argument values are bound to the parameter. Possible values
650 (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300651
Georg Brandl44ea77b2013-03-28 13:28:44 +0100652 .. tabularcolumns:: |l|L|
653
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300654 +------------------------+----------------------------------------------+
655 | Name | Meaning |
656 +========================+==============================================+
657 | *POSITIONAL_ONLY* | Value must be supplied as a positional |
658 | | argument. |
659 | | |
660 | | Python has no explicit syntax for defining |
661 | | positional-only parameters, but many built-in|
662 | | and extension module functions (especially |
663 | | those that accept only one or two parameters)|
664 | | accept them. |
665 +------------------------+----------------------------------------------+
666 | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
667 | | positional argument (this is the standard |
668 | | binding behaviour for functions implemented |
669 | | in Python.) |
670 +------------------------+----------------------------------------------+
671 | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
672 | | bound to any other parameter. This |
673 | | corresponds to a ``*args`` parameter in a |
674 | | Python function definition. |
675 +------------------------+----------------------------------------------+
676 | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
677 | | Keyword only parameters are those which |
678 | | appear after a ``*`` or ``*args`` entry in a |
679 | | Python function definition. |
680 +------------------------+----------------------------------------------+
681 | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
682 | | to any other parameter. This corresponds to a|
683 | | ``**kwargs`` parameter in a Python function |
684 | | definition. |
685 +------------------------+----------------------------------------------+
686
Andrew Svetloveed18082012-08-13 18:23:54 +0300687 Example: print all keyword-only arguments without default values::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300688
689 >>> def foo(a, b, *, c, d=10):
690 ... pass
691
692 >>> sig = signature(foo)
693 >>> for param in sig.parameters.values():
694 ... if (param.kind == param.KEYWORD_ONLY and
695 ... param.default is param.empty):
696 ... print('Parameter:', param)
697 Parameter: c
698
Ezio Melotti8429b672012-09-14 06:35:09 +0300699 .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300700
Georg Brandle4717722012-08-14 09:45:28 +0200701 Create a new Parameter instance based on the instance replaced was invoked
702 on. To override a :class:`Parameter` attribute, pass the corresponding
703 argument. To remove a default value or/and an annotation from a
704 Parameter, pass :attr:`Parameter.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300705
706 ::
707
708 >>> from inspect import Parameter
709 >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
710 >>> str(param)
711 'foo=42'
712
713 >>> str(param.replace()) # Will create a shallow copy of 'param'
714 'foo=42'
715
716 >>> str(param.replace(default=Parameter.empty, annotation='spam'))
717 "foo:'spam'"
718
Yury Selivanov2393dca2014-01-27 15:07:58 -0500719 .. versionchanged:: 3.4
720 In Python 3.3 Parameter objects were allowed to have ``name`` set
721 to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``.
722 This is no longer permitted.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300723
724.. class:: BoundArguments
725
726 Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
727 Holds the mapping of arguments to the function's parameters.
728
729 .. attribute:: BoundArguments.arguments
730
731 An ordered, mutable mapping (:class:`collections.OrderedDict`) of
Georg Brandle4717722012-08-14 09:45:28 +0200732 parameters' names to arguments' values. Contains only explicitly bound
733 arguments. Changes in :attr:`arguments` will reflect in :attr:`args` and
734 :attr:`kwargs`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300735
Georg Brandle4717722012-08-14 09:45:28 +0200736 Should be used in conjunction with :attr:`Signature.parameters` for any
737 argument processing purposes.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300738
739 .. note::
740
741 Arguments for which :meth:`Signature.bind` or
742 :meth:`Signature.bind_partial` relied on a default value are skipped.
Yury Selivanovb907a512015-05-16 13:45:09 -0400743 However, if needed, use :meth:`BoundArguments.apply_defaults` to add
744 them.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300745
746 .. attribute:: BoundArguments.args
747
Georg Brandle4717722012-08-14 09:45:28 +0200748 A tuple of positional arguments values. Dynamically computed from the
749 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300750
751 .. attribute:: BoundArguments.kwargs
752
Georg Brandle4717722012-08-14 09:45:28 +0200753 A dict of keyword arguments values. Dynamically computed from the
754 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300755
Yury Selivanov82796192015-05-14 14:14:02 -0400756 .. attribute:: BoundArguments.signature
757
758 A reference to the parent :class:`Signature` object.
759
Yury Selivanovb907a512015-05-16 13:45:09 -0400760 .. method:: BoundArguments.apply_defaults()
761
762 Set default values for missing arguments.
763
764 For variable-positional arguments (``*args``) the default is an
765 empty tuple.
766
767 For variable-keyword arguments (``**kwargs``) the default is an
768 empty dict.
769
770 ::
771
772 >>> def foo(a, b='ham', *args): pass
773 >>> ba = inspect.signature(foo).bind('spam')
774 >>> ba.apply_defaults()
775 >>> ba.arguments
776 OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])
777
Berker Peksag5b3df5b2015-05-16 23:29:31 +0300778 .. versionadded:: 3.5
779
Georg Brandle4717722012-08-14 09:45:28 +0200780 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
781 functions::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300782
783 def test(a, *, b):
784 ...
785
786 sig = signature(test)
787 ba = sig.bind(10, b=20)
788 test(*ba.args, **ba.kwargs)
789
790
Georg Brandle4717722012-08-14 09:45:28 +0200791.. seealso::
792
793 :pep:`362` - Function Signature Object.
794 The detailed specification, implementation details and examples.
795
796
Georg Brandl116aa622007-08-15 14:28:22 +0000797.. _inspect-classes-functions:
798
799Classes and functions
800---------------------
801
Georg Brandl3dd33882009-06-01 17:35:27 +0000802.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000803
804 Arrange the given list of classes into a hierarchy of nested lists. Where a
805 nested list appears, it contains classes derived from the class whose entry
806 immediately precedes the list. Each entry is a 2-tuple containing a class and a
807 tuple of its base classes. If the *unique* argument is true, exactly one entry
808 appears in the returned structure for each class in the given list. Otherwise,
809 classes using multiple inheritance and their descendants will appear multiple
810 times.
811
812
813.. function:: getargspec(func)
814
Georg Brandl82402752010-01-09 09:48:46 +0000815 Get the names and default values of a Python function's arguments. A
Georg Brandlb30f3302011-01-06 09:23:56 +0000816 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
817 returned. *args* is a list of the argument names. *varargs* and *keywords*
818 are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700819 tuple of default argument values or ``None`` if there are no default
820 arguments; if this tuple has *n* elements, they correspond to the last
821 *n* elements listed in *args*.
Georg Brandl138bcb52007-09-12 19:04:21 +0000822
823 .. deprecated:: 3.0
Yury Selivanov945fff42015-05-22 16:28:05 -0400824 Use :func:`signature` and
825 :ref:`Signature Object <inspect-signature-object>`, which provide a
826 better introspecting API for callables. This function will be removed
827 in Python 3.6.
Georg Brandl138bcb52007-09-12 19:04:21 +0000828
829
830.. function:: getfullargspec(func)
831
Georg Brandl82402752010-01-09 09:48:46 +0000832 Get the names and default values of a Python function's arguments. A
833 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000834
Georg Brandl3dd33882009-06-01 17:35:27 +0000835 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
836 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000837
838 *args* is a list of the argument names. *varargs* and *varkw* are the names
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700839 of the ``*`` and ``**`` arguments or ``None``. *defaults* is an *n*-tuple
840 of the default values of the last *n* arguments, or ``None`` if there are no
841 default arguments. *kwonlyargs* is a list of
Georg Brandl138bcb52007-09-12 19:04:21 +0000842 keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
843 from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
844 names to annotations.
845
846 The first four items in the tuple correspond to :func:`getargspec`.
Georg Brandl116aa622007-08-15 14:28:22 +0000847
Nick Coghlan16355782014-03-08 16:36:37 +1000848 .. versionchanged:: 3.4
849 This function is now based on :func:`signature`, but still ignores
850 ``__wrapped__`` attributes and includes the already bound first
851 parameter in the signature output for bound methods.
852
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400853 .. deprecated:: 3.5
854 Use :func:`signature` and
855 :ref:`Signature Object <inspect-signature-object>`, which provide a
856 better introspecting API for callables.
857
Georg Brandl116aa622007-08-15 14:28:22 +0000858
859.. function:: getargvalues(frame)
860
Georg Brandl3dd33882009-06-01 17:35:27 +0000861 Get information about arguments passed into a particular frame. A
862 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000863 returned. *args* is a list of the argument names. *varargs* and *keywords*
864 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000865 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000866
Yury Selivanov945fff42015-05-22 16:28:05 -0400867 .. deprecated:: 3.5
868 Use :func:`signature` and
869 :ref:`Signature Object <inspect-signature-object>`, which provide a
870 better introspecting API for callables.
871
Georg Brandl116aa622007-08-15 14:28:22 +0000872
Andrew Svetlov735d3172012-10-27 00:28:20 +0300873.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Georg Brandl116aa622007-08-15 14:28:22 +0000874
Michael Foord3af125a2012-04-21 18:22:28 +0100875 Format a pretty argument spec from the values returned by
876 :func:`getargspec` or :func:`getfullargspec`.
877
878 The first seven arguments are (``args``, ``varargs``, ``varkw``,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100879 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
Andrew Svetlov735d3172012-10-27 00:28:20 +0300880
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100881 The other six arguments are functions that are called to turn argument names,
882 ``*`` argument name, ``**`` argument name, default values, return annotation
883 and individual annotations into strings, respectively.
884
885 For example:
886
887 >>> from inspect import formatargspec, getfullargspec
888 >>> def f(a: int, b: float):
889 ... pass
890 ...
891 >>> formatargspec(*getfullargspec(f))
892 '(a: int, b: float)'
Georg Brandl116aa622007-08-15 14:28:22 +0000893
Yury Selivanov945fff42015-05-22 16:28:05 -0400894 .. deprecated:: 3.5
895 Use :func:`signature` and
896 :ref:`Signature Object <inspect-signature-object>`, which provide a
897 better introspecting API for callables.
898
Georg Brandl116aa622007-08-15 14:28:22 +0000899
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000900.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000901
902 Format a pretty argument spec from the four values returned by
903 :func:`getargvalues`. The format\* arguments are the corresponding optional
904 formatting functions that are called to turn names and values into strings.
905
Yury Selivanov945fff42015-05-22 16:28:05 -0400906 .. deprecated:: 3.5
907 Use :func:`signature` and
908 :ref:`Signature Object <inspect-signature-object>`, which provide a
909 better introspecting API for callables.
910
Georg Brandl116aa622007-08-15 14:28:22 +0000911
912.. function:: getmro(cls)
913
914 Return a tuple of class cls's base classes, including cls, in method resolution
915 order. No class appears more than once in this tuple. Note that the method
916 resolution order depends on cls's type. Unless a very peculiar user-defined
917 metatype is in use, cls will be the first element of the tuple.
918
919
Benjamin Peterson3a990c62014-01-02 12:22:30 -0600920.. function:: getcallargs(func, *args, **kwds)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000921
922 Bind the *args* and *kwds* to the argument names of the Python function or
923 method *func*, as if it was called with them. For bound methods, bind also the
924 first argument (typically named ``self``) to the associated instance. A dict
925 is returned, mapping the argument names (including the names of the ``*`` and
926 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
927 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
928 an exception because of incompatible signature, an exception of the same type
929 and the same or similar message is raised. For example::
930
931 >>> from inspect import getcallargs
932 >>> def f(a, b=1, *pos, **named):
933 ... pass
Andrew Svetlove939f382012-08-09 13:25:32 +0300934 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
935 True
936 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
937 True
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000938 >>> getcallargs(f)
939 Traceback (most recent call last):
940 ...
Andrew Svetlove939f382012-08-09 13:25:32 +0300941 TypeError: f() missing 1 required positional argument: 'a'
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000942
943 .. versionadded:: 3.2
944
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400945 .. deprecated:: 3.5
946 Use :meth:`Signature.bind` and :meth:`Signature.bind_partial` instead.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300947
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000948
Nick Coghlan2f92e542012-06-23 19:39:55 +1000949.. function:: getclosurevars(func)
950
951 Get the mapping of external name references in a Python function or
952 method *func* to their current values. A
953 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
954 is returned. *nonlocals* maps referenced names to lexical closure
955 variables, *globals* to the function's module globals and *builtins* to
956 the builtins visible from the function body. *unbound* is the set of names
957 referenced in the function that could not be resolved at all given the
958 current module globals and builtins.
959
960 :exc:`TypeError` is raised if *func* is not a Python function or method.
961
962 .. versionadded:: 3.3
963
964
Nick Coghlane8c45d62013-07-28 20:00:01 +1000965.. function:: unwrap(func, *, stop=None)
966
967 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
968 attributes returning the last object in the chain.
969
970 *stop* is an optional callback accepting an object in the wrapper chain
971 as its sole argument that allows the unwrapping to be terminated early if
972 the callback returns a true value. If the callback never returns a true
973 value, the last object in the chain is returned as usual. For example,
974 :func:`signature` uses this to stop unwrapping if any object in the
975 chain has a ``__signature__`` attribute defined.
976
977 :exc:`ValueError` is raised if a cycle is encountered.
978
979 .. versionadded:: 3.4
980
981
Georg Brandl116aa622007-08-15 14:28:22 +0000982.. _inspect-stack:
983
984The interpreter stack
985---------------------
986
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400987When the following functions return "frame records," each record is a
988:term:`named tuple`
989``FrameInfo(frame, filename, lineno, function, code_context, index)``.
990The tuple contains the frame object, the filename, the line number of the
991current line,
Georg Brandl116aa622007-08-15 14:28:22 +0000992the function name, a list of lines of context from the source code, and the
993index of the current line within that list.
994
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400995.. versionchanged:: 3.5
996 Return a named tuple instead of a tuple.
997
Georg Brandle720c0a2009-04-27 16:20:50 +0000998.. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000999
1000 Keeping references to frame objects, as found in the first element of the frame
1001 records these functions return, can cause your program to create reference
1002 cycles. Once a reference cycle has been created, the lifespan of all objects
1003 which can be accessed from the objects which form the cycle can become much
1004 longer even if Python's optional cycle detector is enabled. If such cycles must
1005 be created, it is important to ensure they are explicitly broken to avoid the
1006 delayed destruction of objects and increased memory consumption which occurs.
1007
1008 Though the cycle detector will catch these, destruction of the frames (and local
1009 variables) can be made deterministic by removing the cycle in a
1010 :keyword:`finally` clause. This is also important if the cycle detector was
1011 disabled when Python was compiled or using :func:`gc.disable`. For example::
1012
1013 def handle_stackframe_without_leak():
1014 frame = inspect.currentframe()
1015 try:
1016 # do something with the frame
1017 finally:
1018 del frame
1019
Antoine Pitrou58720d62013-08-05 23:26:40 +02001020 If you want to keep the frame around (for example to print a traceback
1021 later), you can also break reference cycles by using the
1022 :meth:`frame.clear` method.
1023
Georg Brandl116aa622007-08-15 14:28:22 +00001024The optional *context* argument supported by most of these functions specifies
1025the number of lines of context to return, which are centered around the current
1026line.
1027
1028
Georg Brandl3dd33882009-06-01 17:35:27 +00001029.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001030
Georg Brandl48310cd2009-01-03 21:18:54 +00001031 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +00001032 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +00001033
1034
Georg Brandl3dd33882009-06-01 17:35:27 +00001035.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001036
1037 Get a list of frame records for a frame and all outer frames. These frames
1038 represent the calls that lead to the creation of *frame*. The first entry in the
1039 returned list represents *frame*; the last entry represents the outermost call
1040 on *frame*'s stack.
1041
1042
Georg Brandl3dd33882009-06-01 17:35:27 +00001043.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001044
1045 Get a list of frame records for a traceback's frame and all inner frames. These
1046 frames represent calls made as a consequence of *frame*. The first entry in the
1047 list represents *traceback*; the last entry represents where the exception was
1048 raised.
1049
1050
1051.. function:: currentframe()
1052
1053 Return the frame object for the caller's stack frame.
1054
Georg Brandl495f7b52009-10-27 15:28:25 +00001055 .. impl-detail::
1056
1057 This function relies on Python stack frame support in the interpreter,
1058 which isn't guaranteed to exist in all implementations of Python. If
1059 running in an implementation without Python stack frame support this
1060 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001061
Georg Brandl116aa622007-08-15 14:28:22 +00001062
Georg Brandl3dd33882009-06-01 17:35:27 +00001063.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001064
1065 Return a list of frame records for the caller's stack. The first entry in the
1066 returned list represents the caller; the last entry represents the outermost
1067 call on the stack.
1068
1069
Georg Brandl3dd33882009-06-01 17:35:27 +00001070.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001071
1072 Return a list of frame records for the stack between the current frame and the
1073 frame in which an exception currently being handled was raised in. The first
1074 entry in the list represents the caller; the last entry represents where the
1075 exception was raised.
1076
Michael Foord95fc51d2010-11-20 15:07:30 +00001077
1078Fetching attributes statically
1079------------------------------
1080
1081Both :func:`getattr` and :func:`hasattr` can trigger code execution when
1082fetching or checking for the existence of attributes. Descriptors, like
1083properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
1084may be called.
1085
1086For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +02001087can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +00001088but avoids executing code when it fetches attributes.
1089
1090.. function:: getattr_static(obj, attr, default=None)
1091
1092 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +02001093 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +00001094
1095 Note: this function may not be able to retrieve all attributes
1096 that getattr can fetch (like dynamically created attributes)
1097 and may find attributes that getattr can't (like descriptors
1098 that raise AttributeError). It can also return descriptors objects
1099 instead of instance members.
1100
Serhiy Storchakabfdcd432013-10-13 23:09:14 +03001101 If the instance :attr:`~object.__dict__` is shadowed by another member (for
1102 example a property) then this function will be unable to find instance
1103 members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001104
Michael Foorddcebe0f2011-03-15 19:20:44 -04001105 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +00001106
Éric Araujo941afed2011-09-01 02:47:34 +02001107:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +00001108getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +00001109is returned instead of the underlying attribute.
1110
1111You can handle these with code like the following. Note that
1112for arbitrary getset descriptors invoking these may trigger
1113code execution::
1114
1115 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +00001116 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +00001117 __slots__ = ['foo']
1118
1119 slot_descriptor = type(_foo.foo)
1120 getset_descriptor = type(type(open(__file__)).name)
1121 wrapper_descriptor = type(str.__dict__['__add__'])
1122 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
1123
1124 result = getattr_static(some_object, 'foo')
1125 if type(result) in descriptor_types:
1126 try:
1127 result = result.__get__()
1128 except AttributeError:
1129 # descriptors can raise AttributeError to
1130 # indicate there is no underlying value
1131 # in which case the descriptor itself will
1132 # have to do
1133 pass
Nick Coghlane0f04652010-11-21 03:44:04 +00001134
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001135
Yury Selivanov5376ba92015-06-22 12:19:30 -04001136Current State of Generators and Coroutines
1137------------------------------------------
Nick Coghlane0f04652010-11-21 03:44:04 +00001138
1139When implementing coroutine schedulers and for other advanced uses of
1140generators, it is useful to determine whether a generator is currently
1141executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001142terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +00001143generator to be determined easily.
1144
1145.. function:: getgeneratorstate(generator)
1146
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001147 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +00001148
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001149 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +00001150 * GEN_CREATED: Waiting to start execution.
1151 * GEN_RUNNING: Currently being executed by the interpreter.
1152 * GEN_SUSPENDED: Currently suspended at a yield expression.
1153 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +00001154
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001155 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001156
Yury Selivanov5376ba92015-06-22 12:19:30 -04001157.. function:: getcoroutinestate(coroutine)
1158
1159 Get current state of a coroutine object. The function is intended to be
1160 used with coroutine objects created by :keyword:`async def` functions, but
1161 will accept any coroutine-like object that has ``cr_running`` and
1162 ``cr_frame`` attributes.
1163
1164 Possible states are:
1165 * CORO_CREATED: Waiting to start execution.
1166 * CORO_RUNNING: Currently being executed by the interpreter.
1167 * CORO_SUSPENDED: Currently suspended at an await expression.
1168 * CORO_CLOSED: Execution has completed.
1169
1170 .. versionadded:: 3.5
1171
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001172The current internal state of the generator can also be queried. This is
1173mostly useful for testing purposes, to ensure that internal state is being
1174updated as expected:
1175
1176.. function:: getgeneratorlocals(generator)
1177
1178 Get the mapping of live local variables in *generator* to their current
1179 values. A dictionary is returned that maps from variable names to values.
1180 This is the equivalent of calling :func:`locals` in the body of the
1181 generator, and all the same caveats apply.
1182
1183 If *generator* is a :term:`generator` with no currently associated frame,
1184 then an empty dictionary is returned. :exc:`TypeError` is raised if
1185 *generator* is not a Python generator object.
1186
1187 .. impl-detail::
1188
1189 This function relies on the generator exposing a Python stack frame
1190 for introspection, which isn't guaranteed to be the case in all
1191 implementations of Python. In such cases, this function will always
1192 return an empty dictionary.
1193
1194 .. versionadded:: 3.3
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001195
Yury Selivanov5376ba92015-06-22 12:19:30 -04001196.. function:: getcoroutinelocals(coroutine)
1197
1198 This function is analogous to :func:`~inspect.getgeneratorlocals`, but
1199 works for coroutine objects created by :keyword:`async def` functions.
1200
1201 .. versionadded:: 3.5
1202
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001203
Nick Coghlan367df122013-10-27 01:57:34 +10001204.. _inspect-module-cli:
1205
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001206Command Line Interface
1207----------------------
1208
1209The :mod:`inspect` module also provides a basic introspection capability
1210from the command line.
1211
1212.. program:: inspect
1213
1214By default, accepts the name of a module and prints the source of that
1215module. A class or function within the module can be printed instead by
1216appended a colon and the qualified name of the target object.
1217
1218.. cmdoption:: --details
1219
1220 Print information about the specified object rather than the source code