blob: d21672f75ea1a94f31bb85957f5e2842e2143837 [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 Selivanov5376ba92015-06-22 12:19:30 -0400181| coroutine | __name__ | name |
182+-----------+-----------------+---------------------------+
183| | __qualname__ | qualified name |
184+-----------+-----------------+---------------------------+
Yury Selivanove13f8f32015-07-03 00:23:30 -0400185| | cr_await | object being awaited on, |
186| | | or ``None`` |
187+-----------+-----------------+---------------------------+
Yury Selivanov5376ba92015-06-22 12:19:30 -0400188| | cr_frame | frame |
189+-----------+-----------------+---------------------------+
190| | cr_running | is the coroutine running? |
191+-----------+-----------------+---------------------------+
192| | cr_code | code |
193+-----------+-----------------+---------------------------+
Yury Selivanove13f8f32015-07-03 00:23:30 -0400194| | gi_yieldfrom | object being iterated by |
195| | | ``yield from``, or |
196| | | ``None`` |
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
Victor Stinner4a74a9a2014-06-16 16:25:22 +0200212 Add ``__qualname__`` attribute to generators. The ``__name__`` attribute of
213 generators is now set from the function name, instead of the code name, and
214 it can now be modified.
Victor Stinner40ee3012014-06-16 15:59:28 +0200215
Georg Brandl116aa622007-08-15 14:28:22 +0000216
217.. function:: getmembers(object[, predicate])
218
219 Return all the members of an object in a list of (name, value) pairs sorted by
220 name. If the optional *predicate* argument is supplied, only members for which
221 the predicate returns a true value are included.
222
Christian Heimes7f044312008-01-06 17:05:40 +0000223 .. note::
224
Ethan Furman63c141c2013-10-18 00:27:39 -0700225 :func:`getmembers` will only return class attributes defined in the
226 metaclass when the argument is a class and those attributes have been
227 listed in the metaclass' custom :meth:`__dir__`.
Christian Heimes7f044312008-01-06 17:05:40 +0000228
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230.. function:: getmoduleinfo(path)
231
Georg Brandlb30f3302011-01-06 09:23:56 +0000232 Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode, module_type)``
233 of values that describe how Python will interpret the file identified by
234 *path* if it is a module, or ``None`` if it would not be identified as a
235 module. In that tuple, *name* is the name of the module without the name of
236 any enclosing package, *suffix* is the trailing part of the file name (which
237 may not be a dot-delimited extension), *mode* is the :func:`open` mode that
238 would be used (``'r'`` or ``'rb'``), and *module_type* is an integer giving
239 the type of the module. *module_type* will have a value which can be
240 compared to the constants defined in the :mod:`imp` module; see the
241 documentation for that module for more information on module types.
Georg Brandl116aa622007-08-15 14:28:22 +0000242
Brett Cannoncb66eb02012-05-11 12:58:42 -0400243 .. deprecated:: 3.3
244 You may check the file path's suffix against the supported suffixes
245 listed in :mod:`importlib.machinery` to infer the same information.
246
Georg Brandl116aa622007-08-15 14:28:22 +0000247
248.. function:: getmodulename(path)
249
250 Return the name of the module named by the file *path*, without including the
Nick Coghlan76e07702012-07-18 23:14:57 +1000251 names of enclosing packages. The file extension is checked against all of
252 the entries in :func:`importlib.machinery.all_suffixes`. If it matches,
253 the final path component is returned with the extension removed.
254 Otherwise, ``None`` is returned.
255
256 Note that this function *only* returns a meaningful name for actual
257 Python modules - paths that potentially refer to Python packages will
258 still return ``None``.
259
260 .. versionchanged:: 3.3
261 This function is now based directly on :mod:`importlib` rather than the
262 deprecated :func:`getmoduleinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000263
264
265.. function:: ismodule(object)
266
267 Return true if the object is a module.
268
269
270.. function:: isclass(object)
271
Georg Brandl39cadc32010-10-15 16:53:24 +0000272 Return true if the object is a class, whether built-in or created in Python
273 code.
Georg Brandl116aa622007-08-15 14:28:22 +0000274
275
276.. function:: ismethod(object)
277
Georg Brandl39cadc32010-10-15 16:53:24 +0000278 Return true if the object is a bound method written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280
281.. function:: isfunction(object)
282
Georg Brandl39cadc32010-10-15 16:53:24 +0000283 Return true if the object is a Python function, which includes functions
284 created by a :term:`lambda` expression.
Georg Brandl116aa622007-08-15 14:28:22 +0000285
286
Christian Heimes7131fd92008-02-19 14:21:46 +0000287.. function:: isgeneratorfunction(object)
288
289 Return true if the object is a Python generator function.
290
291
292.. function:: isgenerator(object)
293
294 Return true if the object is a generator.
295
296
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400297.. function:: iscoroutinefunction(object)
298
Yury Selivanov5376ba92015-06-22 12:19:30 -0400299 Return true if the object is a :term:`coroutine function`
300 (a function defined with an :keyword:`async def` syntax).
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400301
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400302 .. versionadded:: 3.5
303
304
305.. function:: iscoroutine(object)
306
Yury Selivanov5376ba92015-06-22 12:19:30 -0400307 Return true if the object is a :term:`coroutine` created by an
308 :keyword:`async def` function.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400309
310 .. versionadded:: 3.5
311
312
Georg Brandl116aa622007-08-15 14:28:22 +0000313.. function:: istraceback(object)
314
315 Return true if the object is a traceback.
316
317
318.. function:: isframe(object)
319
320 Return true if the object is a frame.
321
322
323.. function:: iscode(object)
324
325 Return true if the object is a code.
326
327
328.. function:: isbuiltin(object)
329
Georg Brandl39cadc32010-10-15 16:53:24 +0000330 Return true if the object is a built-in function or a bound built-in method.
Georg Brandl116aa622007-08-15 14:28:22 +0000331
332
333.. function:: isroutine(object)
334
335 Return true if the object is a user-defined or built-in function or method.
336
Georg Brandl39cadc32010-10-15 16:53:24 +0000337
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000338.. function:: isabstract(object)
339
340 Return true if the object is an abstract base class.
341
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343.. function:: ismethoddescriptor(object)
344
Georg Brandl39cadc32010-10-15 16:53:24 +0000345 Return true if the object is a method descriptor, but not if
346 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
347 are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000348
Georg Brandle6bcc912008-05-12 18:05:20 +0000349 This, for example, is true of ``int.__add__``. An object passing this test
350 has a :attr:`__get__` attribute but not a :attr:`__set__` attribute, but
351 beyond that the set of attributes varies. :attr:`__name__` is usually
352 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000353
Georg Brandl9afde1c2007-11-01 20:32:30 +0000354 Methods implemented via descriptors that also pass one of the other tests
355 return false from the :func:`ismethoddescriptor` test, simply because the
356 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000357 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000358
359
360.. function:: isdatadescriptor(object)
361
362 Return true if the object is a data descriptor.
363
Georg Brandl9afde1c2007-11-01 20:32:30 +0000364 Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute.
365 Examples are properties (defined in Python), getsets, and members. The
366 latter two are defined in C and there are more specific tests available for
367 those types, which is robust across Python implementations. Typically, data
368 descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes
369 (properties, getsets, and members have both of these attributes), but this is
370 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000371
Georg Brandl116aa622007-08-15 14:28:22 +0000372
373.. function:: isgetsetdescriptor(object)
374
375 Return true if the object is a getset descriptor.
376
Georg Brandl495f7b52009-10-27 15:28:25 +0000377 .. impl-detail::
378
379 getsets are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000380 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000381 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000382
Georg Brandl116aa622007-08-15 14:28:22 +0000383
384.. function:: ismemberdescriptor(object)
385
386 Return true if the object is a member descriptor.
387
Georg Brandl495f7b52009-10-27 15:28:25 +0000388 .. impl-detail::
389
390 Member descriptors are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000391 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000392 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000393
Georg Brandl116aa622007-08-15 14:28:22 +0000394
395.. _inspect-source:
396
397Retrieving source code
398----------------------
399
Georg Brandl116aa622007-08-15 14:28:22 +0000400.. function:: getdoc(object)
401
Georg Brandl0c77a822008-06-10 16:37:50 +0000402 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Serhiy Storchaka5cf2b722015-04-03 22:38:53 +0300403 If the documentation string for an object is not provided and the object is
404 a class, a method, a property or a descriptor, retrieve the documentation
405 string from the inheritance hierarchy.
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407
408.. function:: getcomments(object)
409
410 Return in a single string any lines of comments immediately preceding the
411 object's source code (for a class, function, or method), or at the top of the
412 Python source file (if the object is a module).
413
414
415.. function:: getfile(object)
416
417 Return the name of the (text or binary) file in which an object was defined.
418 This will fail with a :exc:`TypeError` if the object is a built-in module,
419 class, or function.
420
421
422.. function:: getmodule(object)
423
424 Try to guess which module an object was defined in.
425
426
427.. function:: getsourcefile(object)
428
429 Return the name of the Python source file in which an object was defined. This
430 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
431 function.
432
433
434.. function:: getsourcelines(object)
435
436 Return a list of source lines and starting line number for an object. The
437 argument may be a module, class, method, function, traceback, frame, or code
438 object. The source code is returned as a list of the lines corresponding to the
439 object and the line number indicates where in the original source file the first
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200440 line of code was found. An :exc:`OSError` is raised if the source code cannot
Georg Brandl116aa622007-08-15 14:28:22 +0000441 be retrieved.
442
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200443 .. versionchanged:: 3.3
444 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
445 former.
446
Georg Brandl116aa622007-08-15 14:28:22 +0000447
448.. function:: getsource(object)
449
450 Return the text of the source code for an object. The argument may be a module,
451 class, method, function, traceback, frame, or code object. The source code is
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200452 returned as a single string. An :exc:`OSError` is raised if the source code
Georg Brandl116aa622007-08-15 14:28:22 +0000453 cannot be retrieved.
454
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200455 .. versionchanged:: 3.3
456 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
457 former.
458
Georg Brandl116aa622007-08-15 14:28:22 +0000459
Georg Brandl0c77a822008-06-10 16:37:50 +0000460.. function:: cleandoc(doc)
461
462 Clean up indentation from docstrings that are indented to line up with blocks
463 of code. Any whitespace that can be uniformly removed from the second line
464 onwards is removed. Also, all tabs are expanded to spaces.
465
Georg Brandl0c77a822008-06-10 16:37:50 +0000466
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300467.. _inspect-signature-object:
468
Georg Brandle4717722012-08-14 09:45:28 +0200469Introspecting callables with the Signature object
470-------------------------------------------------
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300471
472.. versionadded:: 3.3
473
Georg Brandle4717722012-08-14 09:45:28 +0200474The Signature object represents the call signature of a callable object and its
475return annotation. To retrieve a Signature object, use the :func:`signature`
476function.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300477
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400478.. function:: signature(callable, \*, follow_wrapped=True)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300479
Georg Brandle4717722012-08-14 09:45:28 +0200480 Return a :class:`Signature` object for the given ``callable``::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300481
482 >>> from inspect import signature
483 >>> def foo(a, *, b:int, **kwargs):
484 ... pass
485
486 >>> sig = signature(foo)
487
488 >>> str(sig)
489 '(a, *, b:int, **kwargs)'
490
491 >>> str(sig.parameters['b'])
492 'b:int'
493
494 >>> sig.parameters['b'].annotation
495 <class 'int'>
496
Georg Brandle4717722012-08-14 09:45:28 +0200497 Accepts a wide range of python callables, from plain functions and classes to
498 :func:`functools.partial` objects.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300499
Larry Hastings5c661892014-01-24 06:17:25 -0800500 Raises :exc:`ValueError` if no signature can be provided, and
501 :exc:`TypeError` if that type of object is not supported.
502
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400503 .. versionadded:: 3.5
504 ``follow_wrapped`` parameter. Pass ``False`` to get a signature of
505 ``callable`` specifically (``callable.__wrapped__`` will not be used to
506 unwrap decorated callables.)
507
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300508 .. note::
509
Georg Brandle4717722012-08-14 09:45:28 +0200510 Some callables may not be introspectable in certain implementations of
Yury Selivanovd71e52f2014-01-30 00:22:57 -0500511 Python. For example, in CPython, some built-in functions defined in
512 C provide no metadata about their arguments.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300513
514
Yury Selivanov78356892014-01-30 00:10:54 -0500515.. class:: Signature(parameters=None, \*, return_annotation=Signature.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300516
Georg Brandle4717722012-08-14 09:45:28 +0200517 A Signature object represents the call signature of a function and its return
518 annotation. For each parameter accepted by the function it stores a
519 :class:`Parameter` object in its :attr:`parameters` collection.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300520
Yury Selivanov78356892014-01-30 00:10:54 -0500521 The optional *parameters* argument is a sequence of :class:`Parameter`
522 objects, which is validated to check that there are no parameters with
523 duplicate names, and that the parameters are in the right order, i.e.
524 positional-only first, then positional-or-keyword, and that parameters with
525 defaults follow parameters without defaults.
526
527 The optional *return_annotation* argument, can be an arbitrary Python object,
528 is the "return" annotation of the callable.
529
Georg Brandle4717722012-08-14 09:45:28 +0200530 Signature objects are *immutable*. Use :meth:`Signature.replace` to make a
531 modified copy.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300532
Yury Selivanov67d727e2014-03-29 13:24:14 -0400533 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400534 Signature objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400535
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300536 .. attribute:: Signature.empty
537
538 A special class-level marker to specify absence of a return annotation.
539
540 .. attribute:: Signature.parameters
541
542 An ordered mapping of parameters' names to the corresponding
543 :class:`Parameter` objects.
544
545 .. attribute:: Signature.return_annotation
546
Georg Brandle4717722012-08-14 09:45:28 +0200547 The "return" annotation for the callable. If the callable has no "return"
548 annotation, this attribute is set to :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300549
550 .. method:: Signature.bind(*args, **kwargs)
551
Georg Brandle4717722012-08-14 09:45:28 +0200552 Create a mapping from positional and keyword arguments to parameters.
553 Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
554 signature, or raises a :exc:`TypeError`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300555
556 .. method:: Signature.bind_partial(*args, **kwargs)
557
Georg Brandle4717722012-08-14 09:45:28 +0200558 Works the same way as :meth:`Signature.bind`, but allows the omission of
559 some required arguments (mimics :func:`functools.partial` behavior.)
560 Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
561 passed arguments do not match the signature.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300562
Ezio Melotti8429b672012-09-14 06:35:09 +0300563 .. method:: Signature.replace(*[, parameters][, return_annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300564
Georg Brandle4717722012-08-14 09:45:28 +0200565 Create a new Signature instance based on the instance replace was invoked
566 on. It is possible to pass different ``parameters`` and/or
567 ``return_annotation`` to override the corresponding properties of the base
568 signature. To remove return_annotation from the copied Signature, pass in
569 :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300570
571 ::
572
573 >>> def test(a, b):
574 ... pass
575 >>> sig = signature(test)
576 >>> new_sig = sig.replace(return_annotation="new return anno")
577 >>> str(new_sig)
578 "(a, b) -> 'new return anno'"
579
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400580 .. classmethod:: Signature.from_callable(obj, \*, follow_wrapped=True)
Yury Selivanovda396452014-03-27 12:09:24 -0400581
582 Return a :class:`Signature` (or its subclass) object for a given callable
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400583 ``obj``. Pass ``follow_wrapped=False`` to get a signature of ``obj``
584 without unwrapping its ``__wrapped__`` chain.
Yury Selivanovda396452014-03-27 12:09:24 -0400585
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400586 This method simplifies subclassing of :class:`Signature`::
Yury Selivanovda396452014-03-27 12:09:24 -0400587
588 class MySignature(Signature):
589 pass
590 sig = MySignature.from_callable(min)
591 assert isinstance(sig, MySignature)
592
Yury Selivanov232b9342014-03-29 13:18:30 -0400593 .. versionadded:: 3.5
594
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300595
Yury Selivanov78356892014-01-30 00:10:54 -0500596.. class:: Parameter(name, kind, \*, default=Parameter.empty, annotation=Parameter.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300597
Georg Brandle4717722012-08-14 09:45:28 +0200598 Parameter objects are *immutable*. Instead of modifying a Parameter object,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300599 you can use :meth:`Parameter.replace` to create a modified copy.
600
Yury Selivanov67d727e2014-03-29 13:24:14 -0400601 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400602 Parameter objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400603
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300604 .. attribute:: Parameter.empty
605
Georg Brandle4717722012-08-14 09:45:28 +0200606 A special class-level marker to specify absence of default values and
607 annotations.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300608
609 .. attribute:: Parameter.name
610
Yury Selivanov2393dca2014-01-27 15:07:58 -0500611 The name of the parameter as a string. The name must be a valid
612 Python identifier.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300613
614 .. attribute:: Parameter.default
615
Georg Brandle4717722012-08-14 09:45:28 +0200616 The default value for the parameter. If the parameter has no default
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300617 value, this attribute is set to :attr:`Parameter.empty`.
618
619 .. attribute:: Parameter.annotation
620
Georg Brandle4717722012-08-14 09:45:28 +0200621 The annotation for the parameter. If the parameter has no annotation,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300622 this attribute is set to :attr:`Parameter.empty`.
623
624 .. attribute:: Parameter.kind
625
Georg Brandle4717722012-08-14 09:45:28 +0200626 Describes how argument values are bound to the parameter. Possible values
627 (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300628
Georg Brandl44ea77b2013-03-28 13:28:44 +0100629 .. tabularcolumns:: |l|L|
630
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300631 +------------------------+----------------------------------------------+
632 | Name | Meaning |
633 +========================+==============================================+
634 | *POSITIONAL_ONLY* | Value must be supplied as a positional |
635 | | argument. |
636 | | |
637 | | Python has no explicit syntax for defining |
638 | | positional-only parameters, but many built-in|
639 | | and extension module functions (especially |
640 | | those that accept only one or two parameters)|
641 | | accept them. |
642 +------------------------+----------------------------------------------+
643 | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
644 | | positional argument (this is the standard |
645 | | binding behaviour for functions implemented |
646 | | in Python.) |
647 +------------------------+----------------------------------------------+
648 | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
649 | | bound to any other parameter. This |
650 | | corresponds to a ``*args`` parameter in a |
651 | | Python function definition. |
652 +------------------------+----------------------------------------------+
653 | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
654 | | Keyword only parameters are those which |
655 | | appear after a ``*`` or ``*args`` entry in a |
656 | | Python function definition. |
657 +------------------------+----------------------------------------------+
658 | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
659 | | to any other parameter. This corresponds to a|
660 | | ``**kwargs`` parameter in a Python function |
661 | | definition. |
662 +------------------------+----------------------------------------------+
663
Andrew Svetloveed18082012-08-13 18:23:54 +0300664 Example: print all keyword-only arguments without default values::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300665
666 >>> def foo(a, b, *, c, d=10):
667 ... pass
668
669 >>> sig = signature(foo)
670 >>> for param in sig.parameters.values():
671 ... if (param.kind == param.KEYWORD_ONLY and
672 ... param.default is param.empty):
673 ... print('Parameter:', param)
674 Parameter: c
675
Ezio Melotti8429b672012-09-14 06:35:09 +0300676 .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300677
Georg Brandle4717722012-08-14 09:45:28 +0200678 Create a new Parameter instance based on the instance replaced was invoked
679 on. To override a :class:`Parameter` attribute, pass the corresponding
680 argument. To remove a default value or/and an annotation from a
681 Parameter, pass :attr:`Parameter.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300682
683 ::
684
685 >>> from inspect import Parameter
686 >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
687 >>> str(param)
688 'foo=42'
689
690 >>> str(param.replace()) # Will create a shallow copy of 'param'
691 'foo=42'
692
693 >>> str(param.replace(default=Parameter.empty, annotation='spam'))
694 "foo:'spam'"
695
Yury Selivanov2393dca2014-01-27 15:07:58 -0500696 .. versionchanged:: 3.4
697 In Python 3.3 Parameter objects were allowed to have ``name`` set
698 to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``.
699 This is no longer permitted.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300700
701.. class:: BoundArguments
702
703 Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
704 Holds the mapping of arguments to the function's parameters.
705
706 .. attribute:: BoundArguments.arguments
707
708 An ordered, mutable mapping (:class:`collections.OrderedDict`) of
Georg Brandle4717722012-08-14 09:45:28 +0200709 parameters' names to arguments' values. Contains only explicitly bound
710 arguments. Changes in :attr:`arguments` will reflect in :attr:`args` and
711 :attr:`kwargs`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300712
Georg Brandle4717722012-08-14 09:45:28 +0200713 Should be used in conjunction with :attr:`Signature.parameters` for any
714 argument processing purposes.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300715
716 .. note::
717
718 Arguments for which :meth:`Signature.bind` or
719 :meth:`Signature.bind_partial` relied on a default value are skipped.
Yury Selivanovb907a512015-05-16 13:45:09 -0400720 However, if needed, use :meth:`BoundArguments.apply_defaults` to add
721 them.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300722
723 .. attribute:: BoundArguments.args
724
Georg Brandle4717722012-08-14 09:45:28 +0200725 A tuple of positional arguments values. Dynamically computed from the
726 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300727
728 .. attribute:: BoundArguments.kwargs
729
Georg Brandle4717722012-08-14 09:45:28 +0200730 A dict of keyword arguments values. Dynamically computed from the
731 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300732
Yury Selivanov82796192015-05-14 14:14:02 -0400733 .. attribute:: BoundArguments.signature
734
735 A reference to the parent :class:`Signature` object.
736
Yury Selivanovb907a512015-05-16 13:45:09 -0400737 .. method:: BoundArguments.apply_defaults()
738
739 Set default values for missing arguments.
740
741 For variable-positional arguments (``*args``) the default is an
742 empty tuple.
743
744 For variable-keyword arguments (``**kwargs``) the default is an
745 empty dict.
746
747 ::
748
749 >>> def foo(a, b='ham', *args): pass
750 >>> ba = inspect.signature(foo).bind('spam')
751 >>> ba.apply_defaults()
752 >>> ba.arguments
753 OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])
754
Berker Peksag5b3df5b2015-05-16 23:29:31 +0300755 .. versionadded:: 3.5
756
Georg Brandle4717722012-08-14 09:45:28 +0200757 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
758 functions::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300759
760 def test(a, *, b):
761 ...
762
763 sig = signature(test)
764 ba = sig.bind(10, b=20)
765 test(*ba.args, **ba.kwargs)
766
767
Georg Brandle4717722012-08-14 09:45:28 +0200768.. seealso::
769
770 :pep:`362` - Function Signature Object.
771 The detailed specification, implementation details and examples.
772
773
Georg Brandl116aa622007-08-15 14:28:22 +0000774.. _inspect-classes-functions:
775
776Classes and functions
777---------------------
778
Georg Brandl3dd33882009-06-01 17:35:27 +0000779.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000780
781 Arrange the given list of classes into a hierarchy of nested lists. Where a
782 nested list appears, it contains classes derived from the class whose entry
783 immediately precedes the list. Each entry is a 2-tuple containing a class and a
784 tuple of its base classes. If the *unique* argument is true, exactly one entry
785 appears in the returned structure for each class in the given list. Otherwise,
786 classes using multiple inheritance and their descendants will appear multiple
787 times.
788
789
790.. function:: getargspec(func)
791
Georg Brandl82402752010-01-09 09:48:46 +0000792 Get the names and default values of a Python function's arguments. A
Georg Brandlb30f3302011-01-06 09:23:56 +0000793 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
794 returned. *args* is a list of the argument names. *varargs* and *keywords*
795 are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700796 tuple of default argument values or ``None`` if there are no default
797 arguments; if this tuple has *n* elements, they correspond to the last
798 *n* elements listed in *args*.
Georg Brandl138bcb52007-09-12 19:04:21 +0000799
800 .. deprecated:: 3.0
Yury Selivanov945fff42015-05-22 16:28:05 -0400801 Use :func:`signature` and
802 :ref:`Signature Object <inspect-signature-object>`, which provide a
803 better introspecting API for callables. This function will be removed
804 in Python 3.6.
Georg Brandl138bcb52007-09-12 19:04:21 +0000805
806
807.. function:: getfullargspec(func)
808
Georg Brandl82402752010-01-09 09:48:46 +0000809 Get the names and default values of a Python function's arguments. A
810 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000811
Georg Brandl3dd33882009-06-01 17:35:27 +0000812 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
813 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000814
815 *args* is a list of the argument names. *varargs* and *varkw* are the names
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700816 of the ``*`` and ``**`` arguments or ``None``. *defaults* is an *n*-tuple
817 of the default values of the last *n* arguments, or ``None`` if there are no
818 default arguments. *kwonlyargs* is a list of
Georg Brandl138bcb52007-09-12 19:04:21 +0000819 keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
820 from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
821 names to annotations.
822
823 The first four items in the tuple correspond to :func:`getargspec`.
Georg Brandl116aa622007-08-15 14:28:22 +0000824
Nick Coghlan16355782014-03-08 16:36:37 +1000825 .. versionchanged:: 3.4
826 This function is now based on :func:`signature`, but still ignores
827 ``__wrapped__`` attributes and includes the already bound first
828 parameter in the signature output for bound methods.
829
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400830 .. deprecated:: 3.5
831 Use :func:`signature` and
832 :ref:`Signature Object <inspect-signature-object>`, which provide a
833 better introspecting API for callables.
834
Georg Brandl116aa622007-08-15 14:28:22 +0000835
836.. function:: getargvalues(frame)
837
Georg Brandl3dd33882009-06-01 17:35:27 +0000838 Get information about arguments passed into a particular frame. A
839 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000840 returned. *args* is a list of the argument names. *varargs* and *keywords*
841 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000842 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000843
Yury Selivanov945fff42015-05-22 16:28:05 -0400844 .. deprecated:: 3.5
845 Use :func:`signature` and
846 :ref:`Signature Object <inspect-signature-object>`, which provide a
847 better introspecting API for callables.
848
Georg Brandl116aa622007-08-15 14:28:22 +0000849
Andrew Svetlov735d3172012-10-27 00:28:20 +0300850.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Georg Brandl116aa622007-08-15 14:28:22 +0000851
Michael Foord3af125a2012-04-21 18:22:28 +0100852 Format a pretty argument spec from the values returned by
853 :func:`getargspec` or :func:`getfullargspec`.
854
855 The first seven arguments are (``args``, ``varargs``, ``varkw``,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100856 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
Andrew Svetlov735d3172012-10-27 00:28:20 +0300857
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100858 The other six arguments are functions that are called to turn argument names,
859 ``*`` argument name, ``**`` argument name, default values, return annotation
860 and individual annotations into strings, respectively.
861
862 For example:
863
864 >>> from inspect import formatargspec, getfullargspec
865 >>> def f(a: int, b: float):
866 ... pass
867 ...
868 >>> formatargspec(*getfullargspec(f))
869 '(a: int, b: float)'
Georg Brandl116aa622007-08-15 14:28:22 +0000870
Yury Selivanov945fff42015-05-22 16:28:05 -0400871 .. deprecated:: 3.5
872 Use :func:`signature` and
873 :ref:`Signature Object <inspect-signature-object>`, which provide a
874 better introspecting API for callables.
875
Georg Brandl116aa622007-08-15 14:28:22 +0000876
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000877.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000878
879 Format a pretty argument spec from the four values returned by
880 :func:`getargvalues`. The format\* arguments are the corresponding optional
881 formatting functions that are called to turn names and values into strings.
882
Yury Selivanov945fff42015-05-22 16:28:05 -0400883 .. deprecated:: 3.5
884 Use :func:`signature` and
885 :ref:`Signature Object <inspect-signature-object>`, which provide a
886 better introspecting API for callables.
887
Georg Brandl116aa622007-08-15 14:28:22 +0000888
889.. function:: getmro(cls)
890
891 Return a tuple of class cls's base classes, including cls, in method resolution
892 order. No class appears more than once in this tuple. Note that the method
893 resolution order depends on cls's type. Unless a very peculiar user-defined
894 metatype is in use, cls will be the first element of the tuple.
895
896
Benjamin Peterson3a990c62014-01-02 12:22:30 -0600897.. function:: getcallargs(func, *args, **kwds)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000898
899 Bind the *args* and *kwds* to the argument names of the Python function or
900 method *func*, as if it was called with them. For bound methods, bind also the
901 first argument (typically named ``self``) to the associated instance. A dict
902 is returned, mapping the argument names (including the names of the ``*`` and
903 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
904 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
905 an exception because of incompatible signature, an exception of the same type
906 and the same or similar message is raised. For example::
907
908 >>> from inspect import getcallargs
909 >>> def f(a, b=1, *pos, **named):
910 ... pass
Andrew Svetlove939f382012-08-09 13:25:32 +0300911 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
912 True
913 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
914 True
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000915 >>> getcallargs(f)
916 Traceback (most recent call last):
917 ...
Andrew Svetlove939f382012-08-09 13:25:32 +0300918 TypeError: f() missing 1 required positional argument: 'a'
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000919
920 .. versionadded:: 3.2
921
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400922 .. deprecated:: 3.5
923 Use :meth:`Signature.bind` and :meth:`Signature.bind_partial` instead.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300924
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000925
Nick Coghlan2f92e542012-06-23 19:39:55 +1000926.. function:: getclosurevars(func)
927
928 Get the mapping of external name references in a Python function or
929 method *func* to their current values. A
930 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
931 is returned. *nonlocals* maps referenced names to lexical closure
932 variables, *globals* to the function's module globals and *builtins* to
933 the builtins visible from the function body. *unbound* is the set of names
934 referenced in the function that could not be resolved at all given the
935 current module globals and builtins.
936
937 :exc:`TypeError` is raised if *func* is not a Python function or method.
938
939 .. versionadded:: 3.3
940
941
Nick Coghlane8c45d62013-07-28 20:00:01 +1000942.. function:: unwrap(func, *, stop=None)
943
944 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
945 attributes returning the last object in the chain.
946
947 *stop* is an optional callback accepting an object in the wrapper chain
948 as its sole argument that allows the unwrapping to be terminated early if
949 the callback returns a true value. If the callback never returns a true
950 value, the last object in the chain is returned as usual. For example,
951 :func:`signature` uses this to stop unwrapping if any object in the
952 chain has a ``__signature__`` attribute defined.
953
954 :exc:`ValueError` is raised if a cycle is encountered.
955
956 .. versionadded:: 3.4
957
958
Georg Brandl116aa622007-08-15 14:28:22 +0000959.. _inspect-stack:
960
961The interpreter stack
962---------------------
963
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400964When the following functions return "frame records," each record is a
965:term:`named tuple`
966``FrameInfo(frame, filename, lineno, function, code_context, index)``.
967The tuple contains the frame object, the filename, the line number of the
968current line,
Georg Brandl116aa622007-08-15 14:28:22 +0000969the function name, a list of lines of context from the source code, and the
970index of the current line within that list.
971
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400972.. versionchanged:: 3.5
973 Return a named tuple instead of a tuple.
974
Georg Brandle720c0a2009-04-27 16:20:50 +0000975.. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000976
977 Keeping references to frame objects, as found in the first element of the frame
978 records these functions return, can cause your program to create reference
979 cycles. Once a reference cycle has been created, the lifespan of all objects
980 which can be accessed from the objects which form the cycle can become much
981 longer even if Python's optional cycle detector is enabled. If such cycles must
982 be created, it is important to ensure they are explicitly broken to avoid the
983 delayed destruction of objects and increased memory consumption which occurs.
984
985 Though the cycle detector will catch these, destruction of the frames (and local
986 variables) can be made deterministic by removing the cycle in a
987 :keyword:`finally` clause. This is also important if the cycle detector was
988 disabled when Python was compiled or using :func:`gc.disable`. For example::
989
990 def handle_stackframe_without_leak():
991 frame = inspect.currentframe()
992 try:
993 # do something with the frame
994 finally:
995 del frame
996
Antoine Pitrou58720d62013-08-05 23:26:40 +0200997 If you want to keep the frame around (for example to print a traceback
998 later), you can also break reference cycles by using the
999 :meth:`frame.clear` method.
1000
Georg Brandl116aa622007-08-15 14:28:22 +00001001The optional *context* argument supported by most of these functions specifies
1002the number of lines of context to return, which are centered around the current
1003line.
1004
1005
Georg Brandl3dd33882009-06-01 17:35:27 +00001006.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001007
Georg Brandl48310cd2009-01-03 21:18:54 +00001008 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +00001009 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +00001010
1011
Georg Brandl3dd33882009-06-01 17:35:27 +00001012.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001013
1014 Get a list of frame records for a frame and all outer frames. These frames
1015 represent the calls that lead to the creation of *frame*. The first entry in the
1016 returned list represents *frame*; the last entry represents the outermost call
1017 on *frame*'s stack.
1018
1019
Georg Brandl3dd33882009-06-01 17:35:27 +00001020.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001021
1022 Get a list of frame records for a traceback's frame and all inner frames. These
1023 frames represent calls made as a consequence of *frame*. The first entry in the
1024 list represents *traceback*; the last entry represents where the exception was
1025 raised.
1026
1027
1028.. function:: currentframe()
1029
1030 Return the frame object for the caller's stack frame.
1031
Georg Brandl495f7b52009-10-27 15:28:25 +00001032 .. impl-detail::
1033
1034 This function relies on Python stack frame support in the interpreter,
1035 which isn't guaranteed to exist in all implementations of Python. If
1036 running in an implementation without Python stack frame support this
1037 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001038
Georg Brandl116aa622007-08-15 14:28:22 +00001039
Georg Brandl3dd33882009-06-01 17:35:27 +00001040.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001041
1042 Return a list of frame records for the caller's stack. The first entry in the
1043 returned list represents the caller; the last entry represents the outermost
1044 call on the stack.
1045
1046
Georg Brandl3dd33882009-06-01 17:35:27 +00001047.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001048
1049 Return a list of frame records for the stack between the current frame and the
1050 frame in which an exception currently being handled was raised in. The first
1051 entry in the list represents the caller; the last entry represents where the
1052 exception was raised.
1053
Michael Foord95fc51d2010-11-20 15:07:30 +00001054
1055Fetching attributes statically
1056------------------------------
1057
1058Both :func:`getattr` and :func:`hasattr` can trigger code execution when
1059fetching or checking for the existence of attributes. Descriptors, like
1060properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
1061may be called.
1062
1063For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +02001064can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +00001065but avoids executing code when it fetches attributes.
1066
1067.. function:: getattr_static(obj, attr, default=None)
1068
1069 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +02001070 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +00001071
1072 Note: this function may not be able to retrieve all attributes
1073 that getattr can fetch (like dynamically created attributes)
1074 and may find attributes that getattr can't (like descriptors
1075 that raise AttributeError). It can also return descriptors objects
1076 instead of instance members.
1077
Serhiy Storchakabfdcd432013-10-13 23:09:14 +03001078 If the instance :attr:`~object.__dict__` is shadowed by another member (for
1079 example a property) then this function will be unable to find instance
1080 members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001081
Michael Foorddcebe0f2011-03-15 19:20:44 -04001082 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +00001083
Éric Araujo941afed2011-09-01 02:47:34 +02001084:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +00001085getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +00001086is returned instead of the underlying attribute.
1087
1088You can handle these with code like the following. Note that
1089for arbitrary getset descriptors invoking these may trigger
1090code execution::
1091
1092 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +00001093 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +00001094 __slots__ = ['foo']
1095
1096 slot_descriptor = type(_foo.foo)
1097 getset_descriptor = type(type(open(__file__)).name)
1098 wrapper_descriptor = type(str.__dict__['__add__'])
1099 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
1100
1101 result = getattr_static(some_object, 'foo')
1102 if type(result) in descriptor_types:
1103 try:
1104 result = result.__get__()
1105 except AttributeError:
1106 # descriptors can raise AttributeError to
1107 # indicate there is no underlying value
1108 # in which case the descriptor itself will
1109 # have to do
1110 pass
Nick Coghlane0f04652010-11-21 03:44:04 +00001111
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001112
Yury Selivanov5376ba92015-06-22 12:19:30 -04001113Current State of Generators and Coroutines
1114------------------------------------------
Nick Coghlane0f04652010-11-21 03:44:04 +00001115
1116When implementing coroutine schedulers and for other advanced uses of
1117generators, it is useful to determine whether a generator is currently
1118executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001119terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +00001120generator to be determined easily.
1121
1122.. function:: getgeneratorstate(generator)
1123
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001124 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +00001125
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001126 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +00001127 * GEN_CREATED: Waiting to start execution.
1128 * GEN_RUNNING: Currently being executed by the interpreter.
1129 * GEN_SUSPENDED: Currently suspended at a yield expression.
1130 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +00001131
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001132 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001133
Yury Selivanov5376ba92015-06-22 12:19:30 -04001134.. function:: getcoroutinestate(coroutine)
1135
1136 Get current state of a coroutine object. The function is intended to be
1137 used with coroutine objects created by :keyword:`async def` functions, but
1138 will accept any coroutine-like object that has ``cr_running`` and
1139 ``cr_frame`` attributes.
1140
1141 Possible states are:
1142 * CORO_CREATED: Waiting to start execution.
1143 * CORO_RUNNING: Currently being executed by the interpreter.
1144 * CORO_SUSPENDED: Currently suspended at an await expression.
1145 * CORO_CLOSED: Execution has completed.
1146
1147 .. versionadded:: 3.5
1148
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001149The current internal state of the generator can also be queried. This is
1150mostly useful for testing purposes, to ensure that internal state is being
1151updated as expected:
1152
1153.. function:: getgeneratorlocals(generator)
1154
1155 Get the mapping of live local variables in *generator* to their current
1156 values. A dictionary is returned that maps from variable names to values.
1157 This is the equivalent of calling :func:`locals` in the body of the
1158 generator, and all the same caveats apply.
1159
1160 If *generator* is a :term:`generator` with no currently associated frame,
1161 then an empty dictionary is returned. :exc:`TypeError` is raised if
1162 *generator* is not a Python generator object.
1163
1164 .. impl-detail::
1165
1166 This function relies on the generator exposing a Python stack frame
1167 for introspection, which isn't guaranteed to be the case in all
1168 implementations of Python. In such cases, this function will always
1169 return an empty dictionary.
1170
1171 .. versionadded:: 3.3
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001172
Yury Selivanov5376ba92015-06-22 12:19:30 -04001173.. function:: getcoroutinelocals(coroutine)
1174
1175 This function is analogous to :func:`~inspect.getgeneratorlocals`, but
1176 works for coroutine objects created by :keyword:`async def` functions.
1177
1178 .. versionadded:: 3.5
1179
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001180
Nick Coghlan367df122013-10-27 01:57:34 +10001181.. _inspect-module-cli:
1182
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001183Command Line Interface
1184----------------------
1185
1186The :mod:`inspect` module also provides a basic introspection capability
1187from the command line.
1188
1189.. program:: inspect
1190
1191By default, accepts the name of a module and prints the source of that
1192module. A class or function within the module can be printed instead by
1193appended a colon and the qualified name of the target object.
1194
1195.. cmdoption:: --details
1196
1197 Print information about the specified object rather than the source code