blob: aa8a181f36bdab3ba9406193eb5be2b8a2004e5b [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`inspect` --- Inspect live objects
2=======================================
3
4.. module:: inspect
5 :synopsis: Extract information and source code from live objects.
6.. moduleauthor:: Ka-Ping Yee <ping@lfw.org>
7.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
8
Raymond Hettinger469271d2011-01-27 20:38:46 +00009**Source code:** :source:`Lib/inspect.py`
10
11--------------
Georg Brandl116aa622007-08-15 14:28:22 +000012
Georg Brandl116aa622007-08-15 14:28:22 +000013The :mod:`inspect` module provides several useful functions to help get
14information about live objects such as modules, classes, methods, functions,
15tracebacks, frame objects, and code objects. For example, it can help you
16examine the contents of a class, retrieve the source code of a method, extract
17and format the argument list for a function, or get all the information you need
18to display a detailed traceback.
19
20There are four main kinds of services provided by this module: type checking,
21getting source code, inspecting classes and functions, and examining the
22interpreter stack.
23
24
25.. _inspect-types:
26
27Types and members
28-----------------
29
30The :func:`getmembers` function retrieves the members of an object such as a
Yury Selivanov59a3b672015-06-30 22:06:42 -040031class or module. The functions whose names begin with "is" are mainly
Georg Brandl116aa622007-08-15 14:28:22 +000032provided as convenient choices for the second argument to :func:`getmembers`.
33They also help you determine when you can expect to find the following special
34attributes:
35
Georg Brandl55ac8f02007-09-01 13:51:09 +000036+-----------+-----------------+---------------------------+
37| Type | Attribute | Description |
38+===========+=================+===========================+
39| module | __doc__ | documentation string |
40+-----------+-----------------+---------------------------+
41| | __file__ | filename (missing for |
42| | | built-in modules) |
43+-----------+-----------------+---------------------------+
44| class | __doc__ | documentation string |
45+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -040046| | __name__ | name with which this |
47| | | class was defined |
48+-----------+-----------------+---------------------------+
49| | __qualname__ | qualified name |
50+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +000051| | __module__ | name of module in which |
52| | | this class was defined |
53+-----------+-----------------+---------------------------+
54| method | __doc__ | documentation string |
55+-----------+-----------------+---------------------------+
56| | __name__ | name with which this |
57| | | method was defined |
58+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -040059| | __qualname__ | qualified name |
60+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000061| | __func__ | function object |
Georg Brandl55ac8f02007-09-01 13:51:09 +000062| | | containing implementation |
63| | | of method |
64+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000065| | __self__ | instance to which this |
Georg Brandl55ac8f02007-09-01 13:51:09 +000066| | | method is bound, or |
67| | | ``None`` |
68+-----------+-----------------+---------------------------+
69| function | __doc__ | documentation string |
70+-----------+-----------------+---------------------------+
71| | __name__ | name with which this |
72| | | function was defined |
73+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -040074| | __qualname__ | qualified name |
75+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +000076| | __code__ | code object containing |
77| | | compiled function |
Georg Brandl9afde1c2007-11-01 20:32:30 +000078| | | :term:`bytecode` |
Georg Brandl55ac8f02007-09-01 13:51:09 +000079+-----------+-----------------+---------------------------+
80| | __defaults__ | tuple of any default |
Yury Selivanovea2d66e2014-01-27 14:26:28 -050081| | | values for positional or |
82| | | keyword parameters |
83+-----------+-----------------+---------------------------+
84| | __kwdefaults__ | mapping of any default |
85| | | values for keyword-only |
86| | | parameters |
Georg Brandl55ac8f02007-09-01 13:51:09 +000087+-----------+-----------------+---------------------------+
88| | __globals__ | global namespace in which |
89| | | this function was defined |
90+-----------+-----------------+---------------------------+
Yury Selivanovc62162d2015-10-31 13:29:15 -040091| | __annotations__ | mapping of parameters |
92| | | names to annotations; |
93| | | ``"return"`` key is |
94| | | reserved for return |
95| | | annotations. |
96+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +000097| traceback | tb_frame | frame object at this |
98| | | level |
99+-----------+-----------------+---------------------------+
100| | tb_lasti | index of last attempted |
101| | | instruction in bytecode |
102+-----------+-----------------+---------------------------+
103| | tb_lineno | current line number in |
104| | | Python source code |
105+-----------+-----------------+---------------------------+
106| | tb_next | next inner traceback |
107| | | object (called by this |
108| | | level) |
109+-----------+-----------------+---------------------------+
110| frame | f_back | next outer frame object |
111| | | (this frame's caller) |
112+-----------+-----------------+---------------------------+
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000113| | f_builtins | builtins namespace seen |
Georg Brandl55ac8f02007-09-01 13:51:09 +0000114| | | by this frame |
115+-----------+-----------------+---------------------------+
116| | f_code | code object being |
117| | | executed in this frame |
118+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000119| | f_globals | global namespace seen by |
120| | | this frame |
121+-----------+-----------------+---------------------------+
122| | f_lasti | index of last attempted |
123| | | instruction in bytecode |
124+-----------+-----------------+---------------------------+
125| | f_lineno | current line number in |
126| | | Python source code |
127+-----------+-----------------+---------------------------+
128| | f_locals | local namespace seen by |
129| | | this frame |
130+-----------+-----------------+---------------------------+
131| | f_restricted | 0 or 1 if frame is in |
132| | | restricted execution mode |
133+-----------+-----------------+---------------------------+
134| | f_trace | tracing function for this |
135| | | frame, or ``None`` |
136+-----------+-----------------+---------------------------+
137| code | co_argcount | number of arguments (not |
138| | | including \* or \*\* |
139| | | args) |
140+-----------+-----------------+---------------------------+
141| | co_code | string of raw compiled |
142| | | bytecode |
143+-----------+-----------------+---------------------------+
144| | co_consts | tuple of constants used |
145| | | in the bytecode |
146+-----------+-----------------+---------------------------+
147| | co_filename | name of file in which |
148| | | this code object was |
149| | | created |
150+-----------+-----------------+---------------------------+
151| | co_firstlineno | number of first line in |
152| | | Python source code |
153+-----------+-----------------+---------------------------+
154| | co_flags | bitmap: 1=optimized ``|`` |
155| | | 2=newlocals ``|`` 4=\*arg |
156| | | ``|`` 8=\*\*arg |
157+-----------+-----------------+---------------------------+
158| | co_lnotab | encoded mapping of line |
159| | | numbers to bytecode |
160| | | indices |
161+-----------+-----------------+---------------------------+
162| | co_name | name with which this code |
163| | | object was defined |
164+-----------+-----------------+---------------------------+
165| | co_names | tuple of names of local |
166| | | variables |
167+-----------+-----------------+---------------------------+
168| | co_nlocals | number of local variables |
169+-----------+-----------------+---------------------------+
170| | co_stacksize | virtual machine stack |
171| | | space required |
172+-----------+-----------------+---------------------------+
173| | co_varnames | tuple of names of |
174| | | arguments and local |
175| | | variables |
176+-----------+-----------------+---------------------------+
Victor Stinner40ee3012014-06-16 15:59:28 +0200177| generator | __name__ | name |
178+-----------+-----------------+---------------------------+
179| | __qualname__ | qualified name |
180+-----------+-----------------+---------------------------+
181| | gi_frame | frame |
182+-----------+-----------------+---------------------------+
183| | gi_running | is the generator running? |
184+-----------+-----------------+---------------------------+
185| | gi_code | code |
186+-----------+-----------------+---------------------------+
Yury Selivanovc135f0a2015-08-17 13:02:42 -0400187| | gi_yieldfrom | object being iterated by |
188| | | ``yield from``, or |
189| | | ``None`` |
190+-----------+-----------------+---------------------------+
Yury Selivanov5376ba92015-06-22 12:19:30 -0400191| coroutine | __name__ | name |
192+-----------+-----------------+---------------------------+
193| | __qualname__ | qualified name |
194+-----------+-----------------+---------------------------+
Yury Selivanove13f8f32015-07-03 00:23:30 -0400195| | cr_await | object being awaited on, |
196| | | or ``None`` |
197+-----------+-----------------+---------------------------+
Yury Selivanov5376ba92015-06-22 12:19:30 -0400198| | cr_frame | frame |
199+-----------+-----------------+---------------------------+
200| | cr_running | is the coroutine running? |
201+-----------+-----------------+---------------------------+
202| | cr_code | code |
203+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000204| builtin | __doc__ | documentation string |
205+-----------+-----------------+---------------------------+
206| | __name__ | original name of this |
207| | | function or method |
208+-----------+-----------------+---------------------------+
Yury Selivanov03395682015-05-30 13:53:49 -0400209| | __qualname__ | qualified name |
210+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000211| | __self__ | instance to which a |
212| | | method is bound, or |
213| | | ``None`` |
214+-----------+-----------------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000215
Victor Stinner40ee3012014-06-16 15:59:28 +0200216.. versionchanged:: 3.5
217
Yury Selivanov5fbad3c2015-08-17 13:04:41 -0400218 Add ``__qualname__`` and ``gi_yieldfrom`` attributes to generators.
219
220 The ``__name__`` attribute of generators is now set from the function
221 name, instead of the code name, and it can now be modified.
Victor Stinner40ee3012014-06-16 15:59:28 +0200222
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224.. function:: getmembers(object[, predicate])
225
226 Return all the members of an object in a list of (name, value) pairs sorted by
227 name. If the optional *predicate* argument is supplied, only members for which
228 the predicate returns a true value are included.
229
Christian Heimes7f044312008-01-06 17:05:40 +0000230 .. note::
231
Ethan Furman63c141c2013-10-18 00:27:39 -0700232 :func:`getmembers` will only return class attributes defined in the
233 metaclass when the argument is a class and those attributes have been
234 listed in the metaclass' custom :meth:`__dir__`.
Christian Heimes7f044312008-01-06 17:05:40 +0000235
Georg Brandl116aa622007-08-15 14:28:22 +0000236
Georg Brandl116aa622007-08-15 14:28:22 +0000237.. function:: getmodulename(path)
238
239 Return the name of the module named by the file *path*, without including the
Nick Coghlan76e07702012-07-18 23:14:57 +1000240 names of enclosing packages. The file extension is checked against all of
241 the entries in :func:`importlib.machinery.all_suffixes`. If it matches,
242 the final path component is returned with the extension removed.
243 Otherwise, ``None`` is returned.
244
245 Note that this function *only* returns a meaningful name for actual
246 Python modules - paths that potentially refer to Python packages will
247 still return ``None``.
248
249 .. versionchanged:: 3.3
Yury Selivanov6dfbc5d2015-07-23 17:49:00 +0300250 The function is based directly on :mod:`importlib`.
Georg Brandl116aa622007-08-15 14:28:22 +0000251
252
253.. function:: ismodule(object)
254
255 Return true if the object is a module.
256
257
258.. function:: isclass(object)
259
Georg Brandl39cadc32010-10-15 16:53:24 +0000260 Return true if the object is a class, whether built-in or created in Python
261 code.
Georg Brandl116aa622007-08-15 14:28:22 +0000262
263
264.. function:: ismethod(object)
265
Georg Brandl39cadc32010-10-15 16:53:24 +0000266 Return true if the object is a bound method written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268
269.. function:: isfunction(object)
270
Georg Brandl39cadc32010-10-15 16:53:24 +0000271 Return true if the object is a Python function, which includes functions
272 created by a :term:`lambda` expression.
Georg Brandl116aa622007-08-15 14:28:22 +0000273
274
Christian Heimes7131fd92008-02-19 14:21:46 +0000275.. function:: isgeneratorfunction(object)
276
277 Return true if the object is a Python generator function.
278
279
280.. function:: isgenerator(object)
281
282 Return true if the object is a generator.
283
284
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400285.. function:: iscoroutinefunction(object)
286
Yury Selivanov5376ba92015-06-22 12:19:30 -0400287 Return true if the object is a :term:`coroutine function`
288 (a function defined with an :keyword:`async def` syntax).
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400289
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400290 .. versionadded:: 3.5
291
292
293.. function:: iscoroutine(object)
294
Yury Selivanov5376ba92015-06-22 12:19:30 -0400295 Return true if the object is a :term:`coroutine` created by an
296 :keyword:`async def` function.
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400297
298 .. versionadded:: 3.5
299
300
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400301.. function:: isawaitable(object)
302
303 Return true if the object can be used in :keyword:`await` expression.
304
305 Can also be used to distinguish generator-based coroutines from regular
306 generators::
307
308 def gen():
309 yield
310 @types.coroutine
311 def gen_coro():
312 yield
313
314 assert not isawaitable(gen())
315 assert isawaitable(gen_coro())
316
317 .. versionadded:: 3.5
318
319
Georg Brandl116aa622007-08-15 14:28:22 +0000320.. function:: istraceback(object)
321
322 Return true if the object is a traceback.
323
324
325.. function:: isframe(object)
326
327 Return true if the object is a frame.
328
329
330.. function:: iscode(object)
331
332 Return true if the object is a code.
333
334
335.. function:: isbuiltin(object)
336
Georg Brandl39cadc32010-10-15 16:53:24 +0000337 Return true if the object is a built-in function or a bound built-in method.
Georg Brandl116aa622007-08-15 14:28:22 +0000338
339
340.. function:: isroutine(object)
341
342 Return true if the object is a user-defined or built-in function or method.
343
Georg Brandl39cadc32010-10-15 16:53:24 +0000344
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000345.. function:: isabstract(object)
346
347 Return true if the object is an abstract base class.
348
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350.. function:: ismethoddescriptor(object)
351
Georg Brandl39cadc32010-10-15 16:53:24 +0000352 Return true if the object is a method descriptor, but not if
353 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
354 are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000355
Georg Brandle6bcc912008-05-12 18:05:20 +0000356 This, for example, is true of ``int.__add__``. An object passing this test
357 has a :attr:`__get__` attribute but not a :attr:`__set__` attribute, but
358 beyond that the set of attributes varies. :attr:`__name__` is usually
359 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Georg Brandl9afde1c2007-11-01 20:32:30 +0000361 Methods implemented via descriptors that also pass one of the other tests
362 return false from the :func:`ismethoddescriptor` test, simply because the
363 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000364 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000365
366
367.. function:: isdatadescriptor(object)
368
369 Return true if the object is a data descriptor.
370
Georg Brandl9afde1c2007-11-01 20:32:30 +0000371 Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute.
372 Examples are properties (defined in Python), getsets, and members. The
373 latter two are defined in C and there are more specific tests available for
374 those types, which is robust across Python implementations. Typically, data
375 descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes
376 (properties, getsets, and members have both of these attributes), but this is
377 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000378
Georg Brandl116aa622007-08-15 14:28:22 +0000379
380.. function:: isgetsetdescriptor(object)
381
382 Return true if the object is a getset descriptor.
383
Georg Brandl495f7b52009-10-27 15:28:25 +0000384 .. impl-detail::
385
386 getsets are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000387 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000388 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000389
Georg Brandl116aa622007-08-15 14:28:22 +0000390
391.. function:: ismemberdescriptor(object)
392
393 Return true if the object is a member descriptor.
394
Georg Brandl495f7b52009-10-27 15:28:25 +0000395 .. impl-detail::
396
397 Member descriptors are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000398 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000399 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000400
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402.. _inspect-source:
403
404Retrieving source code
405----------------------
406
Georg Brandl116aa622007-08-15 14:28:22 +0000407.. function:: getdoc(object)
408
Georg Brandl0c77a822008-06-10 16:37:50 +0000409 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300410 If the documentation string for an object is not provided and the object is
411 a class, a method, a property or a descriptor, retrieve the documentation
412 string from the inheritance hierarchy.
Georg Brandl116aa622007-08-15 14:28:22 +0000413
Berker Peksag4333d8b2015-07-30 18:06:09 +0300414 .. versionchanged:: 3.5
415 Documentation strings are now inherited if not overridden.
416
Georg Brandl116aa622007-08-15 14:28:22 +0000417
418.. function:: getcomments(object)
419
420 Return in a single string any lines of comments immediately preceding the
421 object's source code (for a class, function, or method), or at the top of the
422 Python source file (if the object is a module).
423
424
425.. function:: getfile(object)
426
427 Return the name of the (text or binary) file in which an object was defined.
428 This will fail with a :exc:`TypeError` if the object is a built-in module,
429 class, or function.
430
431
432.. function:: getmodule(object)
433
434 Try to guess which module an object was defined in.
435
436
437.. function:: getsourcefile(object)
438
439 Return the name of the Python source file in which an object was defined. This
440 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
441 function.
442
443
444.. function:: getsourcelines(object)
445
446 Return a list of source lines and starting line number for an object. The
447 argument may be a module, class, method, function, traceback, frame, or code
448 object. The source code is returned as a list of the lines corresponding to the
449 object and the line number indicates where in the original source file the first
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200450 line of code was found. An :exc:`OSError` is raised if the source code cannot
Georg Brandl116aa622007-08-15 14:28:22 +0000451 be retrieved.
452
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200453 .. versionchanged:: 3.3
454 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
455 former.
456
Georg Brandl116aa622007-08-15 14:28:22 +0000457
458.. function:: getsource(object)
459
460 Return the text of the source code for an object. The argument may be a module,
461 class, method, function, traceback, frame, or code object. The source code is
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200462 returned as a single string. An :exc:`OSError` is raised if the source code
Georg Brandl116aa622007-08-15 14:28:22 +0000463 cannot be retrieved.
464
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200465 .. versionchanged:: 3.3
466 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
467 former.
468
Georg Brandl116aa622007-08-15 14:28:22 +0000469
Georg Brandl0c77a822008-06-10 16:37:50 +0000470.. function:: cleandoc(doc)
471
472 Clean up indentation from docstrings that are indented to line up with blocks
473 of code. Any whitespace that can be uniformly removed from the second line
474 onwards is removed. Also, all tabs are expanded to spaces.
475
Georg Brandl0c77a822008-06-10 16:37:50 +0000476
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300477.. _inspect-signature-object:
478
Georg Brandle4717722012-08-14 09:45:28 +0200479Introspecting callables with the Signature object
480-------------------------------------------------
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300481
482.. versionadded:: 3.3
483
Georg Brandle4717722012-08-14 09:45:28 +0200484The Signature object represents the call signature of a callable object and its
485return annotation. To retrieve a Signature object, use the :func:`signature`
486function.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300487
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400488.. function:: signature(callable, \*, follow_wrapped=True)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300489
Georg Brandle4717722012-08-14 09:45:28 +0200490 Return a :class:`Signature` object for the given ``callable``::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300491
492 >>> from inspect import signature
493 >>> def foo(a, *, b:int, **kwargs):
494 ... pass
495
496 >>> sig = signature(foo)
497
498 >>> str(sig)
499 '(a, *, b:int, **kwargs)'
500
501 >>> str(sig.parameters['b'])
502 'b:int'
503
504 >>> sig.parameters['b'].annotation
505 <class 'int'>
506
Georg Brandle4717722012-08-14 09:45:28 +0200507 Accepts a wide range of python callables, from plain functions and classes to
508 :func:`functools.partial` objects.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300509
Larry Hastings5c661892014-01-24 06:17:25 -0800510 Raises :exc:`ValueError` if no signature can be provided, and
511 :exc:`TypeError` if that type of object is not supported.
512
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400513 .. versionadded:: 3.5
514 ``follow_wrapped`` parameter. Pass ``False`` to get a signature of
515 ``callable`` specifically (``callable.__wrapped__`` will not be used to
516 unwrap decorated callables.)
517
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300518 .. note::
519
Georg Brandle4717722012-08-14 09:45:28 +0200520 Some callables may not be introspectable in certain implementations of
Yury Selivanovd71e52f2014-01-30 00:22:57 -0500521 Python. For example, in CPython, some built-in functions defined in
522 C provide no metadata about their arguments.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300523
524
Yury Selivanov78356892014-01-30 00:10:54 -0500525.. class:: Signature(parameters=None, \*, return_annotation=Signature.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300526
Georg Brandle4717722012-08-14 09:45:28 +0200527 A Signature object represents the call signature of a function and its return
528 annotation. For each parameter accepted by the function it stores a
529 :class:`Parameter` object in its :attr:`parameters` collection.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300530
Yury Selivanov78356892014-01-30 00:10:54 -0500531 The optional *parameters* argument is a sequence of :class:`Parameter`
532 objects, which is validated to check that there are no parameters with
533 duplicate names, and that the parameters are in the right order, i.e.
534 positional-only first, then positional-or-keyword, and that parameters with
535 defaults follow parameters without defaults.
536
537 The optional *return_annotation* argument, can be an arbitrary Python object,
538 is the "return" annotation of the callable.
539
Georg Brandle4717722012-08-14 09:45:28 +0200540 Signature objects are *immutable*. Use :meth:`Signature.replace` to make a
541 modified copy.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300542
Yury Selivanov67d727e2014-03-29 13:24:14 -0400543 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400544 Signature objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400545
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300546 .. attribute:: Signature.empty
547
548 A special class-level marker to specify absence of a return annotation.
549
550 .. attribute:: Signature.parameters
551
552 An ordered mapping of parameters' names to the corresponding
553 :class:`Parameter` objects.
554
555 .. attribute:: Signature.return_annotation
556
Georg Brandle4717722012-08-14 09:45:28 +0200557 The "return" annotation for the callable. If the callable has no "return"
558 annotation, this attribute is set to :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300559
560 .. method:: Signature.bind(*args, **kwargs)
561
Georg Brandle4717722012-08-14 09:45:28 +0200562 Create a mapping from positional and keyword arguments to parameters.
563 Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
564 signature, or raises a :exc:`TypeError`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300565
566 .. method:: Signature.bind_partial(*args, **kwargs)
567
Georg Brandle4717722012-08-14 09:45:28 +0200568 Works the same way as :meth:`Signature.bind`, but allows the omission of
569 some required arguments (mimics :func:`functools.partial` behavior.)
570 Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
571 passed arguments do not match the signature.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300572
Ezio Melotti8429b672012-09-14 06:35:09 +0300573 .. method:: Signature.replace(*[, parameters][, return_annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300574
Georg Brandle4717722012-08-14 09:45:28 +0200575 Create a new Signature instance based on the instance replace was invoked
576 on. It is possible to pass different ``parameters`` and/or
577 ``return_annotation`` to override the corresponding properties of the base
578 signature. To remove return_annotation from the copied Signature, pass in
579 :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300580
581 ::
582
583 >>> def test(a, b):
584 ... pass
585 >>> sig = signature(test)
586 >>> new_sig = sig.replace(return_annotation="new return anno")
587 >>> str(new_sig)
588 "(a, b) -> 'new return anno'"
589
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400590 .. classmethod:: Signature.from_callable(obj, \*, follow_wrapped=True)
Yury Selivanovda396452014-03-27 12:09:24 -0400591
592 Return a :class:`Signature` (or its subclass) object for a given callable
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400593 ``obj``. Pass ``follow_wrapped=False`` to get a signature of ``obj``
594 without unwrapping its ``__wrapped__`` chain.
Yury Selivanovda396452014-03-27 12:09:24 -0400595
Yury Selivanovbcd4fc12015-05-20 14:30:08 -0400596 This method simplifies subclassing of :class:`Signature`::
Yury Selivanovda396452014-03-27 12:09:24 -0400597
598 class MySignature(Signature):
599 pass
600 sig = MySignature.from_callable(min)
601 assert isinstance(sig, MySignature)
602
Yury Selivanov232b9342014-03-29 13:18:30 -0400603 .. versionadded:: 3.5
604
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300605
Yury Selivanov78356892014-01-30 00:10:54 -0500606.. class:: Parameter(name, kind, \*, default=Parameter.empty, annotation=Parameter.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300607
Georg Brandle4717722012-08-14 09:45:28 +0200608 Parameter objects are *immutable*. Instead of modifying a Parameter object,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300609 you can use :meth:`Parameter.replace` to create a modified copy.
610
Yury Selivanov67d727e2014-03-29 13:24:14 -0400611 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400612 Parameter objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400613
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300614 .. attribute:: Parameter.empty
615
Georg Brandle4717722012-08-14 09:45:28 +0200616 A special class-level marker to specify absence of default values and
617 annotations.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300618
619 .. attribute:: Parameter.name
620
Yury Selivanov2393dca2014-01-27 15:07:58 -0500621 The name of the parameter as a string. The name must be a valid
622 Python identifier.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300623
624 .. attribute:: Parameter.default
625
Georg Brandle4717722012-08-14 09:45:28 +0200626 The default value for the parameter. If the parameter has no default
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300627 value, this attribute is set to :attr:`Parameter.empty`.
628
629 .. attribute:: Parameter.annotation
630
Georg Brandle4717722012-08-14 09:45:28 +0200631 The annotation for the parameter. If the parameter has no annotation,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300632 this attribute is set to :attr:`Parameter.empty`.
633
634 .. attribute:: Parameter.kind
635
Georg Brandle4717722012-08-14 09:45:28 +0200636 Describes how argument values are bound to the parameter. Possible values
637 (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300638
Georg Brandl44ea77b2013-03-28 13:28:44 +0100639 .. tabularcolumns:: |l|L|
640
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300641 +------------------------+----------------------------------------------+
642 | Name | Meaning |
643 +========================+==============================================+
644 | *POSITIONAL_ONLY* | Value must be supplied as a positional |
645 | | argument. |
646 | | |
647 | | Python has no explicit syntax for defining |
648 | | positional-only parameters, but many built-in|
649 | | and extension module functions (especially |
650 | | those that accept only one or two parameters)|
651 | | accept them. |
652 +------------------------+----------------------------------------------+
653 | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
654 | | positional argument (this is the standard |
655 | | binding behaviour for functions implemented |
656 | | in Python.) |
657 +------------------------+----------------------------------------------+
658 | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
659 | | bound to any other parameter. This |
660 | | corresponds to a ``*args`` parameter in a |
661 | | Python function definition. |
662 +------------------------+----------------------------------------------+
663 | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
664 | | Keyword only parameters are those which |
665 | | appear after a ``*`` or ``*args`` entry in a |
666 | | Python function definition. |
667 +------------------------+----------------------------------------------+
668 | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
669 | | to any other parameter. This corresponds to a|
670 | | ``**kwargs`` parameter in a Python function |
671 | | definition. |
672 +------------------------+----------------------------------------------+
673
Andrew Svetloveed18082012-08-13 18:23:54 +0300674 Example: print all keyword-only arguments without default values::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300675
676 >>> def foo(a, b, *, c, d=10):
677 ... pass
678
679 >>> sig = signature(foo)
680 >>> for param in sig.parameters.values():
681 ... if (param.kind == param.KEYWORD_ONLY and
682 ... param.default is param.empty):
683 ... print('Parameter:', param)
684 Parameter: c
685
Ezio Melotti8429b672012-09-14 06:35:09 +0300686 .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300687
Georg Brandle4717722012-08-14 09:45:28 +0200688 Create a new Parameter instance based on the instance replaced was invoked
689 on. To override a :class:`Parameter` attribute, pass the corresponding
690 argument. To remove a default value or/and an annotation from a
691 Parameter, pass :attr:`Parameter.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300692
693 ::
694
695 >>> from inspect import Parameter
696 >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
697 >>> str(param)
698 'foo=42'
699
700 >>> str(param.replace()) # Will create a shallow copy of 'param'
701 'foo=42'
702
703 >>> str(param.replace(default=Parameter.empty, annotation='spam'))
704 "foo:'spam'"
705
Yury Selivanov2393dca2014-01-27 15:07:58 -0500706 .. versionchanged:: 3.4
707 In Python 3.3 Parameter objects were allowed to have ``name`` set
708 to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``.
709 This is no longer permitted.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300710
711.. class:: BoundArguments
712
713 Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
714 Holds the mapping of arguments to the function's parameters.
715
716 .. attribute:: BoundArguments.arguments
717
718 An ordered, mutable mapping (:class:`collections.OrderedDict`) of
Georg Brandle4717722012-08-14 09:45:28 +0200719 parameters' names to arguments' values. Contains only explicitly bound
720 arguments. Changes in :attr:`arguments` will reflect in :attr:`args` and
721 :attr:`kwargs`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300722
Georg Brandle4717722012-08-14 09:45:28 +0200723 Should be used in conjunction with :attr:`Signature.parameters` for any
724 argument processing purposes.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300725
726 .. note::
727
728 Arguments for which :meth:`Signature.bind` or
729 :meth:`Signature.bind_partial` relied on a default value are skipped.
Yury Selivanovb907a512015-05-16 13:45:09 -0400730 However, if needed, use :meth:`BoundArguments.apply_defaults` to add
731 them.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300732
733 .. attribute:: BoundArguments.args
734
Georg Brandle4717722012-08-14 09:45:28 +0200735 A tuple of positional arguments values. Dynamically computed from the
736 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300737
738 .. attribute:: BoundArguments.kwargs
739
Georg Brandle4717722012-08-14 09:45:28 +0200740 A dict of keyword arguments values. Dynamically computed from the
741 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300742
Yury Selivanov82796192015-05-14 14:14:02 -0400743 .. attribute:: BoundArguments.signature
744
745 A reference to the parent :class:`Signature` object.
746
Yury Selivanovb907a512015-05-16 13:45:09 -0400747 .. method:: BoundArguments.apply_defaults()
748
749 Set default values for missing arguments.
750
751 For variable-positional arguments (``*args``) the default is an
752 empty tuple.
753
754 For variable-keyword arguments (``**kwargs``) the default is an
755 empty dict.
756
757 ::
758
759 >>> def foo(a, b='ham', *args): pass
760 >>> ba = inspect.signature(foo).bind('spam')
761 >>> ba.apply_defaults()
762 >>> ba.arguments
763 OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])
764
Berker Peksag5b3df5b2015-05-16 23:29:31 +0300765 .. versionadded:: 3.5
766
Georg Brandle4717722012-08-14 09:45:28 +0200767 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
768 functions::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300769
770 def test(a, *, b):
771 ...
772
773 sig = signature(test)
774 ba = sig.bind(10, b=20)
775 test(*ba.args, **ba.kwargs)
776
777
Georg Brandle4717722012-08-14 09:45:28 +0200778.. seealso::
779
780 :pep:`362` - Function Signature Object.
781 The detailed specification, implementation details and examples.
782
783
Georg Brandl116aa622007-08-15 14:28:22 +0000784.. _inspect-classes-functions:
785
786Classes and functions
787---------------------
788
Georg Brandl3dd33882009-06-01 17:35:27 +0000789.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000790
791 Arrange the given list of classes into a hierarchy of nested lists. Where a
792 nested list appears, it contains classes derived from the class whose entry
793 immediately precedes the list. Each entry is a 2-tuple containing a class and a
794 tuple of its base classes. If the *unique* argument is true, exactly one entry
795 appears in the returned structure for each class in the given list. Otherwise,
796 classes using multiple inheritance and their descendants will appear multiple
797 times.
798
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500799
800.. function:: getargspec(func)
801
802 Get the names and default values of a Python function's arguments. A
803 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
804 returned. *args* is a list of the argument names. *varargs* and *keywords*
805 are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a
806 tuple of default argument values or ``None`` if there are no default
807 arguments; if this tuple has *n* elements, they correspond to the last
808 *n* elements listed in *args*.
809
810 .. deprecated:: 3.0
811 Use :func:`signature` and
812 :ref:`Signature Object <inspect-signature-object>`, which provide a
Yury Selivanova7c159d2016-01-11 21:04:50 -0500813 better introspecting API for callables.
Yury Selivanov37dc2b22016-01-11 15:15:01 -0500814
815
Georg Brandl138bcb52007-09-12 19:04:21 +0000816.. function:: getfullargspec(func)
817
Georg Brandl82402752010-01-09 09:48:46 +0000818 Get the names and default values of a Python function's arguments. A
819 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000820
Georg Brandl3dd33882009-06-01 17:35:27 +0000821 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
822 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000823
824 *args* is a list of the argument names. *varargs* and *varkw* are the names
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700825 of the ``*`` and ``**`` arguments or ``None``. *defaults* is an *n*-tuple
826 of the default values of the last *n* arguments, or ``None`` if there are no
827 default arguments. *kwonlyargs* is a list of
Georg Brandl138bcb52007-09-12 19:04:21 +0000828 keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
829 from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
830 names to annotations.
831
Nick Coghlan16355782014-03-08 16:36:37 +1000832 .. versionchanged:: 3.4
833 This function is now based on :func:`signature`, but still ignores
834 ``__wrapped__`` attributes and includes the already bound first
835 parameter in the signature output for bound methods.
836
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400837 .. deprecated:: 3.5
838 Use :func:`signature` and
839 :ref:`Signature Object <inspect-signature-object>`, which provide a
840 better introspecting API for callables.
841
Georg Brandl116aa622007-08-15 14:28:22 +0000842
843.. function:: getargvalues(frame)
844
Georg Brandl3dd33882009-06-01 17:35:27 +0000845 Get information about arguments passed into a particular frame. A
846 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000847 returned. *args* is a list of the argument names. *varargs* and *keywords*
848 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000849 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000850
Yury Selivanov945fff42015-05-22 16:28:05 -0400851 .. deprecated:: 3.5
852 Use :func:`signature` and
853 :ref:`Signature Object <inspect-signature-object>`, which provide a
854 better introspecting API for callables.
855
Georg Brandl116aa622007-08-15 14:28:22 +0000856
Andrew Svetlov735d3172012-10-27 00:28:20 +0300857.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Georg Brandl116aa622007-08-15 14:28:22 +0000858
Michael Foord3af125a2012-04-21 18:22:28 +0100859 Format a pretty argument spec from the values returned by
Berker Peksagfa3922c2015-07-31 04:11:29 +0300860 :func:`getfullargspec`.
Michael Foord3af125a2012-04-21 18:22:28 +0100861
862 The first seven arguments are (``args``, ``varargs``, ``varkw``,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100863 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
Andrew Svetlov735d3172012-10-27 00:28:20 +0300864
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100865 The other six arguments are functions that are called to turn argument names,
866 ``*`` argument name, ``**`` argument name, default values, return annotation
867 and individual annotations into strings, respectively.
868
869 For example:
870
871 >>> from inspect import formatargspec, getfullargspec
872 >>> def f(a: int, b: float):
873 ... pass
874 ...
875 >>> formatargspec(*getfullargspec(f))
876 '(a: int, b: float)'
Georg Brandl116aa622007-08-15 14:28:22 +0000877
Yury Selivanov945fff42015-05-22 16:28:05 -0400878 .. deprecated:: 3.5
879 Use :func:`signature` and
880 :ref:`Signature Object <inspect-signature-object>`, which provide a
881 better introspecting API for callables.
882
Georg Brandl116aa622007-08-15 14:28:22 +0000883
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000884.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000885
886 Format a pretty argument spec from the four values returned by
887 :func:`getargvalues`. The format\* arguments are the corresponding optional
888 formatting functions that are called to turn names and values into strings.
889
Yury Selivanov945fff42015-05-22 16:28:05 -0400890 .. deprecated:: 3.5
891 Use :func:`signature` and
892 :ref:`Signature Object <inspect-signature-object>`, which provide a
893 better introspecting API for callables.
894
Georg Brandl116aa622007-08-15 14:28:22 +0000895
896.. function:: getmro(cls)
897
898 Return a tuple of class cls's base classes, including cls, in method resolution
899 order. No class appears more than once in this tuple. Note that the method
900 resolution order depends on cls's type. Unless a very peculiar user-defined
901 metatype is in use, cls will be the first element of the tuple.
902
903
Benjamin Peterson3a990c62014-01-02 12:22:30 -0600904.. function:: getcallargs(func, *args, **kwds)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000905
906 Bind the *args* and *kwds* to the argument names of the Python function or
907 method *func*, as if it was called with them. For bound methods, bind also the
908 first argument (typically named ``self``) to the associated instance. A dict
909 is returned, mapping the argument names (including the names of the ``*`` and
910 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
911 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
912 an exception because of incompatible signature, an exception of the same type
913 and the same or similar message is raised. For example::
914
915 >>> from inspect import getcallargs
916 >>> def f(a, b=1, *pos, **named):
917 ... pass
Andrew Svetlove939f382012-08-09 13:25:32 +0300918 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
919 True
920 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
921 True
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000922 >>> getcallargs(f)
923 Traceback (most recent call last):
924 ...
Andrew Svetlove939f382012-08-09 13:25:32 +0300925 TypeError: f() missing 1 required positional argument: 'a'
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000926
927 .. versionadded:: 3.2
928
Yury Selivanov3cfec2e2015-05-22 11:38:38 -0400929 .. deprecated:: 3.5
930 Use :meth:`Signature.bind` and :meth:`Signature.bind_partial` instead.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300931
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000932
Nick Coghlan2f92e542012-06-23 19:39:55 +1000933.. function:: getclosurevars(func)
934
935 Get the mapping of external name references in a Python function or
936 method *func* to their current values. A
937 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
938 is returned. *nonlocals* maps referenced names to lexical closure
939 variables, *globals* to the function's module globals and *builtins* to
940 the builtins visible from the function body. *unbound* is the set of names
941 referenced in the function that could not be resolved at all given the
942 current module globals and builtins.
943
944 :exc:`TypeError` is raised if *func* is not a Python function or method.
945
946 .. versionadded:: 3.3
947
948
Nick Coghlane8c45d62013-07-28 20:00:01 +1000949.. function:: unwrap(func, *, stop=None)
950
951 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
952 attributes returning the last object in the chain.
953
954 *stop* is an optional callback accepting an object in the wrapper chain
955 as its sole argument that allows the unwrapping to be terminated early if
956 the callback returns a true value. If the callback never returns a true
957 value, the last object in the chain is returned as usual. For example,
958 :func:`signature` uses this to stop unwrapping if any object in the
959 chain has a ``__signature__`` attribute defined.
960
961 :exc:`ValueError` is raised if a cycle is encountered.
962
963 .. versionadded:: 3.4
964
965
Georg Brandl116aa622007-08-15 14:28:22 +0000966.. _inspect-stack:
967
968The interpreter stack
969---------------------
970
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400971When the following functions return "frame records," each record is a
972:term:`named tuple`
973``FrameInfo(frame, filename, lineno, function, code_context, index)``.
974The tuple contains the frame object, the filename, the line number of the
975current line,
Georg Brandl116aa622007-08-15 14:28:22 +0000976the function name, a list of lines of context from the source code, and the
977index of the current line within that list.
978
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400979.. versionchanged:: 3.5
980 Return a named tuple instead of a tuple.
981
Georg Brandle720c0a2009-04-27 16:20:50 +0000982.. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000983
984 Keeping references to frame objects, as found in the first element of the frame
985 records these functions return, can cause your program to create reference
986 cycles. Once a reference cycle has been created, the lifespan of all objects
987 which can be accessed from the objects which form the cycle can become much
988 longer even if Python's optional cycle detector is enabled. If such cycles must
989 be created, it is important to ensure they are explicitly broken to avoid the
990 delayed destruction of objects and increased memory consumption which occurs.
991
992 Though the cycle detector will catch these, destruction of the frames (and local
993 variables) can be made deterministic by removing the cycle in a
994 :keyword:`finally` clause. This is also important if the cycle detector was
995 disabled when Python was compiled or using :func:`gc.disable`. For example::
996
997 def handle_stackframe_without_leak():
998 frame = inspect.currentframe()
999 try:
1000 # do something with the frame
1001 finally:
1002 del frame
1003
Antoine Pitrou58720d62013-08-05 23:26:40 +02001004 If you want to keep the frame around (for example to print a traceback
1005 later), you can also break reference cycles by using the
1006 :meth:`frame.clear` method.
1007
Georg Brandl116aa622007-08-15 14:28:22 +00001008The optional *context* argument supported by most of these functions specifies
1009the number of lines of context to return, which are centered around the current
1010line.
1011
1012
Georg Brandl3dd33882009-06-01 17:35:27 +00001013.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001014
Georg Brandl48310cd2009-01-03 21:18:54 +00001015 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +00001016 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +00001017
1018
Georg Brandl3dd33882009-06-01 17:35:27 +00001019.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001020
1021 Get a list of frame records for a frame and all outer frames. These frames
1022 represent the calls that lead to the creation of *frame*. The first entry in the
1023 returned list represents *frame*; the last entry represents the outermost call
1024 on *frame*'s stack.
1025
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001026 .. versionchanged:: 3.5
1027 A list of :term:`named tuples <named tuple>`
1028 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1029 is returned.
1030
Georg Brandl116aa622007-08-15 14:28:22 +00001031
Georg Brandl3dd33882009-06-01 17:35:27 +00001032.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001033
1034 Get a list of frame records for a traceback's frame and all inner frames. These
1035 frames represent calls made as a consequence of *frame*. The first entry in the
1036 list represents *traceback*; the last entry represents where the exception was
1037 raised.
1038
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001039 .. versionchanged:: 3.5
1040 A list of :term:`named tuples <named tuple>`
1041 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1042 is returned.
1043
Georg Brandl116aa622007-08-15 14:28:22 +00001044
1045.. function:: currentframe()
1046
1047 Return the frame object for the caller's stack frame.
1048
Georg Brandl495f7b52009-10-27 15:28:25 +00001049 .. impl-detail::
1050
1051 This function relies on Python stack frame support in the interpreter,
1052 which isn't guaranteed to exist in all implementations of Python. If
1053 running in an implementation without Python stack frame support this
1054 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001055
Georg Brandl116aa622007-08-15 14:28:22 +00001056
Georg Brandl3dd33882009-06-01 17:35:27 +00001057.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001058
1059 Return a list of frame records for the caller's stack. The first entry in the
1060 returned list represents the caller; the last entry represents the outermost
1061 call on the stack.
1062
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001063 .. versionchanged:: 3.5
1064 A list of :term:`named tuples <named tuple>`
1065 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1066 is returned.
1067
Georg Brandl116aa622007-08-15 14:28:22 +00001068
Georg Brandl3dd33882009-06-01 17:35:27 +00001069.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +00001070
1071 Return a list of frame records for the stack between the current frame and the
1072 frame in which an exception currently being handled was raised in. The first
1073 entry in the list represents the caller; the last entry represents where the
1074 exception was raised.
1075
Yury Selivanov100fc3f2015-09-08 22:40:30 -04001076 .. versionchanged:: 3.5
1077 A list of :term:`named tuples <named tuple>`
1078 ``FrameInfo(frame, filename, lineno, function, code_context, index)``
1079 is returned.
1080
Michael Foord95fc51d2010-11-20 15:07:30 +00001081
1082Fetching attributes statically
1083------------------------------
1084
1085Both :func:`getattr` and :func:`hasattr` can trigger code execution when
1086fetching or checking for the existence of attributes. Descriptors, like
1087properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
1088may be called.
1089
1090For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +02001091can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +00001092but avoids executing code when it fetches attributes.
1093
1094.. function:: getattr_static(obj, attr, default=None)
1095
1096 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +02001097 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +00001098
1099 Note: this function may not be able to retrieve all attributes
1100 that getattr can fetch (like dynamically created attributes)
1101 and may find attributes that getattr can't (like descriptors
1102 that raise AttributeError). It can also return descriptors objects
1103 instead of instance members.
1104
Serhiy Storchakabfdcd432013-10-13 23:09:14 +03001105 If the instance :attr:`~object.__dict__` is shadowed by another member (for
1106 example a property) then this function will be unable to find instance
1107 members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001108
Michael Foorddcebe0f2011-03-15 19:20:44 -04001109 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +00001110
Éric Araujo941afed2011-09-01 02:47:34 +02001111:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +00001112getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +00001113is returned instead of the underlying attribute.
1114
1115You can handle these with code like the following. Note that
1116for arbitrary getset descriptors invoking these may trigger
1117code execution::
1118
1119 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +00001120 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +00001121 __slots__ = ['foo']
1122
1123 slot_descriptor = type(_foo.foo)
1124 getset_descriptor = type(type(open(__file__)).name)
1125 wrapper_descriptor = type(str.__dict__['__add__'])
1126 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
1127
1128 result = getattr_static(some_object, 'foo')
1129 if type(result) in descriptor_types:
1130 try:
1131 result = result.__get__()
1132 except AttributeError:
1133 # descriptors can raise AttributeError to
1134 # indicate there is no underlying value
1135 # in which case the descriptor itself will
1136 # have to do
1137 pass
Nick Coghlane0f04652010-11-21 03:44:04 +00001138
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001139
Yury Selivanov5376ba92015-06-22 12:19:30 -04001140Current State of Generators and Coroutines
1141------------------------------------------
Nick Coghlane0f04652010-11-21 03:44:04 +00001142
1143When implementing coroutine schedulers and for other advanced uses of
1144generators, it is useful to determine whether a generator is currently
1145executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001146terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +00001147generator to be determined easily.
1148
1149.. function:: getgeneratorstate(generator)
1150
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001151 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +00001152
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001153 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +00001154 * GEN_CREATED: Waiting to start execution.
1155 * GEN_RUNNING: Currently being executed by the interpreter.
1156 * GEN_SUSPENDED: Currently suspended at a yield expression.
1157 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +00001158
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001159 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001160
Yury Selivanov5376ba92015-06-22 12:19:30 -04001161.. function:: getcoroutinestate(coroutine)
1162
1163 Get current state of a coroutine object. The function is intended to be
1164 used with coroutine objects created by :keyword:`async def` functions, but
1165 will accept any coroutine-like object that has ``cr_running`` and
1166 ``cr_frame`` attributes.
1167
1168 Possible states are:
1169 * CORO_CREATED: Waiting to start execution.
1170 * CORO_RUNNING: Currently being executed by the interpreter.
1171 * CORO_SUSPENDED: Currently suspended at an await expression.
1172 * CORO_CLOSED: Execution has completed.
1173
1174 .. versionadded:: 3.5
1175
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001176The current internal state of the generator can also be queried. This is
1177mostly useful for testing purposes, to ensure that internal state is being
1178updated as expected:
1179
1180.. function:: getgeneratorlocals(generator)
1181
1182 Get the mapping of live local variables in *generator* to their current
1183 values. A dictionary is returned that maps from variable names to values.
1184 This is the equivalent of calling :func:`locals` in the body of the
1185 generator, and all the same caveats apply.
1186
1187 If *generator* is a :term:`generator` with no currently associated frame,
1188 then an empty dictionary is returned. :exc:`TypeError` is raised if
1189 *generator* is not a Python generator object.
1190
1191 .. impl-detail::
1192
1193 This function relies on the generator exposing a Python stack frame
1194 for introspection, which isn't guaranteed to be the case in all
1195 implementations of Python. In such cases, this function will always
1196 return an empty dictionary.
1197
1198 .. versionadded:: 3.3
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001199
Yury Selivanov5376ba92015-06-22 12:19:30 -04001200.. function:: getcoroutinelocals(coroutine)
1201
1202 This function is analogous to :func:`~inspect.getgeneratorlocals`, but
1203 works for coroutine objects created by :keyword:`async def` functions.
1204
1205 .. versionadded:: 3.5
1206
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001207
Nick Coghlan367df122013-10-27 01:57:34 +10001208.. _inspect-module-cli:
1209
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001210Command Line Interface
1211----------------------
1212
1213The :mod:`inspect` module also provides a basic introspection capability
1214from the command line.
1215
1216.. program:: inspect
1217
1218By default, accepts the name of a module and prints the source of that
1219module. A class or function within the module can be printed instead by
1220appended a colon and the qualified name of the target object.
1221
1222.. cmdoption:: --details
1223
1224 Print information about the specified object rather than the source code