blob: 41c61b79374dfbbf00068d9bdc11924084017d30 [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
Christian Heimes78644762008-03-04 23:39:23 +000031class or module. The sixteen 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+-----------+-----------------+---------------------------+
46| | __module__ | name of module in which |
47| | | this class was defined |
48+-----------+-----------------+---------------------------+
49| method | __doc__ | documentation string |
50+-----------+-----------------+---------------------------+
51| | __name__ | name with which this |
52| | | method was defined |
53+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000054| | __func__ | function object |
Georg Brandl55ac8f02007-09-01 13:51:09 +000055| | | containing implementation |
56| | | of method |
57+-----------+-----------------+---------------------------+
Christian Heimesff737952007-11-27 10:40:20 +000058| | __self__ | instance to which this |
Georg Brandl55ac8f02007-09-01 13:51:09 +000059| | | method is bound, or |
60| | | ``None`` |
61+-----------+-----------------+---------------------------+
62| function | __doc__ | documentation string |
63+-----------+-----------------+---------------------------+
64| | __name__ | name with which this |
65| | | function was defined |
66+-----------+-----------------+---------------------------+
67| | __code__ | code object containing |
68| | | compiled function |
Georg Brandl9afde1c2007-11-01 20:32:30 +000069| | | :term:`bytecode` |
Georg Brandl55ac8f02007-09-01 13:51:09 +000070+-----------+-----------------+---------------------------+
71| | __defaults__ | tuple of any default |
72| | | values for arguments |
73+-----------+-----------------+---------------------------+
74| | __globals__ | global namespace in which |
75| | | this function was defined |
76+-----------+-----------------+---------------------------+
77| traceback | tb_frame | frame object at this |
78| | | level |
79+-----------+-----------------+---------------------------+
80| | tb_lasti | index of last attempted |
81| | | instruction in bytecode |
82+-----------+-----------------+---------------------------+
83| | tb_lineno | current line number in |
84| | | Python source code |
85+-----------+-----------------+---------------------------+
86| | tb_next | next inner traceback |
87| | | object (called by this |
88| | | level) |
89+-----------+-----------------+---------------------------+
90| frame | f_back | next outer frame object |
91| | | (this frame's caller) |
92+-----------+-----------------+---------------------------+
Georg Brandlc4a55fc2010-02-06 18:46:57 +000093| | f_builtins | builtins namespace seen |
Georg Brandl55ac8f02007-09-01 13:51:09 +000094| | | by this frame |
95+-----------+-----------------+---------------------------+
96| | f_code | code object being |
97| | | executed in this frame |
98+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +000099| | f_globals | global namespace seen by |
100| | | this frame |
101+-----------+-----------------+---------------------------+
102| | f_lasti | index of last attempted |
103| | | instruction in bytecode |
104+-----------+-----------------+---------------------------+
105| | f_lineno | current line number in |
106| | | Python source code |
107+-----------+-----------------+---------------------------+
108| | f_locals | local namespace seen by |
109| | | this frame |
110+-----------+-----------------+---------------------------+
111| | f_restricted | 0 or 1 if frame is in |
112| | | restricted execution mode |
113+-----------+-----------------+---------------------------+
114| | f_trace | tracing function for this |
115| | | frame, or ``None`` |
116+-----------+-----------------+---------------------------+
117| code | co_argcount | number of arguments (not |
118| | | including \* or \*\* |
119| | | args) |
120+-----------+-----------------+---------------------------+
121| | co_code | string of raw compiled |
122| | | bytecode |
123+-----------+-----------------+---------------------------+
124| | co_consts | tuple of constants used |
125| | | in the bytecode |
126+-----------+-----------------+---------------------------+
127| | co_filename | name of file in which |
128| | | this code object was |
129| | | created |
130+-----------+-----------------+---------------------------+
131| | co_firstlineno | number of first line in |
132| | | Python source code |
133+-----------+-----------------+---------------------------+
134| | co_flags | bitmap: 1=optimized ``|`` |
135| | | 2=newlocals ``|`` 4=\*arg |
136| | | ``|`` 8=\*\*arg |
137+-----------+-----------------+---------------------------+
138| | co_lnotab | encoded mapping of line |
139| | | numbers to bytecode |
140| | | indices |
141+-----------+-----------------+---------------------------+
142| | co_name | name with which this code |
143| | | object was defined |
144+-----------+-----------------+---------------------------+
145| | co_names | tuple of names of local |
146| | | variables |
147+-----------+-----------------+---------------------------+
148| | co_nlocals | number of local variables |
149+-----------+-----------------+---------------------------+
150| | co_stacksize | virtual machine stack |
151| | | space required |
152+-----------+-----------------+---------------------------+
153| | co_varnames | tuple of names of |
154| | | arguments and local |
155| | | variables |
156+-----------+-----------------+---------------------------+
157| builtin | __doc__ | documentation string |
158+-----------+-----------------+---------------------------+
159| | __name__ | original name of this |
160| | | function or method |
161+-----------+-----------------+---------------------------+
162| | __self__ | instance to which a |
163| | | method is bound, or |
164| | | ``None`` |
165+-----------+-----------------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000166
167
168.. function:: getmembers(object[, predicate])
169
170 Return all the members of an object in a list of (name, value) pairs sorted by
171 name. If the optional *predicate* argument is supplied, only members for which
172 the predicate returns a true value are included.
173
Christian Heimes7f044312008-01-06 17:05:40 +0000174 .. note::
175
Ethan Furman63c141c2013-10-18 00:27:39 -0700176 :func:`getmembers` will only return class attributes defined in the
177 metaclass when the argument is a class and those attributes have been
178 listed in the metaclass' custom :meth:`__dir__`.
Christian Heimes7f044312008-01-06 17:05:40 +0000179
Georg Brandl116aa622007-08-15 14:28:22 +0000180
181.. function:: getmoduleinfo(path)
182
Georg Brandlb30f3302011-01-06 09:23:56 +0000183 Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode, module_type)``
184 of values that describe how Python will interpret the file identified by
185 *path* if it is a module, or ``None`` if it would not be identified as a
186 module. In that tuple, *name* is the name of the module without the name of
187 any enclosing package, *suffix* is the trailing part of the file name (which
188 may not be a dot-delimited extension), *mode* is the :func:`open` mode that
189 would be used (``'r'`` or ``'rb'``), and *module_type* is an integer giving
190 the type of the module. *module_type* will have a value which can be
191 compared to the constants defined in the :mod:`imp` module; see the
192 documentation for that module for more information on module types.
Georg Brandl116aa622007-08-15 14:28:22 +0000193
Brett Cannoncb66eb02012-05-11 12:58:42 -0400194 .. deprecated:: 3.3
195 You may check the file path's suffix against the supported suffixes
196 listed in :mod:`importlib.machinery` to infer the same information.
197
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199.. function:: getmodulename(path)
200
201 Return the name of the module named by the file *path*, without including the
Nick Coghlan76e07702012-07-18 23:14:57 +1000202 names of enclosing packages. The file extension is checked against all of
203 the entries in :func:`importlib.machinery.all_suffixes`. If it matches,
204 the final path component is returned with the extension removed.
205 Otherwise, ``None`` is returned.
206
207 Note that this function *only* returns a meaningful name for actual
208 Python modules - paths that potentially refer to Python packages will
209 still return ``None``.
210
211 .. versionchanged:: 3.3
212 This function is now based directly on :mod:`importlib` rather than the
213 deprecated :func:`getmoduleinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000214
215
216.. function:: ismodule(object)
217
218 Return true if the object is a module.
219
220
221.. function:: isclass(object)
222
Georg Brandl39cadc32010-10-15 16:53:24 +0000223 Return true if the object is a class, whether built-in or created in Python
224 code.
Georg Brandl116aa622007-08-15 14:28:22 +0000225
226
227.. function:: ismethod(object)
228
Georg Brandl39cadc32010-10-15 16:53:24 +0000229 Return true if the object is a bound method written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000230
231
232.. function:: isfunction(object)
233
Georg Brandl39cadc32010-10-15 16:53:24 +0000234 Return true if the object is a Python function, which includes functions
235 created by a :term:`lambda` expression.
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237
Christian Heimes7131fd92008-02-19 14:21:46 +0000238.. function:: isgeneratorfunction(object)
239
240 Return true if the object is a Python generator function.
241
242
243.. function:: isgenerator(object)
244
245 Return true if the object is a generator.
246
247
Georg Brandl116aa622007-08-15 14:28:22 +0000248.. function:: istraceback(object)
249
250 Return true if the object is a traceback.
251
252
253.. function:: isframe(object)
254
255 Return true if the object is a frame.
256
257
258.. function:: iscode(object)
259
260 Return true if the object is a code.
261
262
263.. function:: isbuiltin(object)
264
Georg Brandl39cadc32010-10-15 16:53:24 +0000265 Return true if the object is a built-in function or a bound built-in method.
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267
268.. function:: isroutine(object)
269
270 Return true if the object is a user-defined or built-in function or method.
271
Georg Brandl39cadc32010-10-15 16:53:24 +0000272
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000273.. function:: isabstract(object)
274
275 Return true if the object is an abstract base class.
276
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278.. function:: ismethoddescriptor(object)
279
Georg Brandl39cadc32010-10-15 16:53:24 +0000280 Return true if the object is a method descriptor, but not if
281 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
282 are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000283
Georg Brandle6bcc912008-05-12 18:05:20 +0000284 This, for example, is true of ``int.__add__``. An object passing this test
285 has a :attr:`__get__` attribute but not a :attr:`__set__` attribute, but
286 beyond that the set of attributes varies. :attr:`__name__` is usually
287 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000288
Georg Brandl9afde1c2007-11-01 20:32:30 +0000289 Methods implemented via descriptors that also pass one of the other tests
290 return false from the :func:`ismethoddescriptor` test, simply because the
291 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000292 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000293
294
295.. function:: isdatadescriptor(object)
296
297 Return true if the object is a data descriptor.
298
Georg Brandl9afde1c2007-11-01 20:32:30 +0000299 Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute.
300 Examples are properties (defined in Python), getsets, and members. The
301 latter two are defined in C and there are more specific tests available for
302 those types, which is robust across Python implementations. Typically, data
303 descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes
304 (properties, getsets, and members have both of these attributes), but this is
305 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000306
Georg Brandl116aa622007-08-15 14:28:22 +0000307
308.. function:: isgetsetdescriptor(object)
309
310 Return true if the object is a getset descriptor.
311
Georg Brandl495f7b52009-10-27 15:28:25 +0000312 .. impl-detail::
313
314 getsets are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000315 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000316 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000317
Georg Brandl116aa622007-08-15 14:28:22 +0000318
319.. function:: ismemberdescriptor(object)
320
321 Return true if the object is a member descriptor.
322
Georg Brandl495f7b52009-10-27 15:28:25 +0000323 .. impl-detail::
324
325 Member descriptors are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000326 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000327 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000328
Georg Brandl116aa622007-08-15 14:28:22 +0000329
330.. _inspect-source:
331
332Retrieving source code
333----------------------
334
Georg Brandl116aa622007-08-15 14:28:22 +0000335.. function:: getdoc(object)
336
Georg Brandl0c77a822008-06-10 16:37:50 +0000337 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Georg Brandl116aa622007-08-15 14:28:22 +0000338
339
340.. function:: getcomments(object)
341
342 Return in a single string any lines of comments immediately preceding the
343 object's source code (for a class, function, or method), or at the top of the
344 Python source file (if the object is a module).
345
346
347.. function:: getfile(object)
348
349 Return the name of the (text or binary) file in which an object was defined.
350 This will fail with a :exc:`TypeError` if the object is a built-in module,
351 class, or function.
352
353
354.. function:: getmodule(object)
355
356 Try to guess which module an object was defined in.
357
358
359.. function:: getsourcefile(object)
360
361 Return the name of the Python source file in which an object was defined. This
362 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
363 function.
364
365
366.. function:: getsourcelines(object)
367
368 Return a list of source lines and starting line number for an object. The
369 argument may be a module, class, method, function, traceback, frame, or code
370 object. The source code is returned as a list of the lines corresponding to the
371 object and the line number indicates where in the original source file the first
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200372 line of code was found. An :exc:`OSError` is raised if the source code cannot
Georg Brandl116aa622007-08-15 14:28:22 +0000373 be retrieved.
374
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200375 .. versionchanged:: 3.3
376 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
377 former.
378
Georg Brandl116aa622007-08-15 14:28:22 +0000379
380.. function:: getsource(object)
381
382 Return the text of the source code for an object. The argument may be a module,
383 class, method, function, traceback, frame, or code object. The source code is
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200384 returned as a single string. An :exc:`OSError` is raised if the source code
Georg Brandl116aa622007-08-15 14:28:22 +0000385 cannot be retrieved.
386
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200387 .. versionchanged:: 3.3
388 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
389 former.
390
Georg Brandl116aa622007-08-15 14:28:22 +0000391
Georg Brandl0c77a822008-06-10 16:37:50 +0000392.. function:: cleandoc(doc)
393
394 Clean up indentation from docstrings that are indented to line up with blocks
395 of code. Any whitespace that can be uniformly removed from the second line
396 onwards is removed. Also, all tabs are expanded to spaces.
397
Georg Brandl0c77a822008-06-10 16:37:50 +0000398
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300399.. _inspect-signature-object:
400
Georg Brandle4717722012-08-14 09:45:28 +0200401Introspecting callables with the Signature object
402-------------------------------------------------
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300403
404.. versionadded:: 3.3
405
Georg Brandle4717722012-08-14 09:45:28 +0200406The Signature object represents the call signature of a callable object and its
407return annotation. To retrieve a Signature object, use the :func:`signature`
408function.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300409
410.. function:: signature(callable)
411
Georg Brandle4717722012-08-14 09:45:28 +0200412 Return a :class:`Signature` object for the given ``callable``::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300413
414 >>> from inspect import signature
415 >>> def foo(a, *, b:int, **kwargs):
416 ... pass
417
418 >>> sig = signature(foo)
419
420 >>> str(sig)
421 '(a, *, b:int, **kwargs)'
422
423 >>> str(sig.parameters['b'])
424 'b:int'
425
426 >>> sig.parameters['b'].annotation
427 <class 'int'>
428
Georg Brandle4717722012-08-14 09:45:28 +0200429 Accepts a wide range of python callables, from plain functions and classes to
430 :func:`functools.partial` objects.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300431
432 .. note::
433
Georg Brandle4717722012-08-14 09:45:28 +0200434 Some callables may not be introspectable in certain implementations of
435 Python. For example, in CPython, built-in functions defined in C provide
436 no metadata about their arguments.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300437
438
439.. class:: Signature
440
Georg Brandle4717722012-08-14 09:45:28 +0200441 A Signature object represents the call signature of a function and its return
442 annotation. For each parameter accepted by the function it stores a
443 :class:`Parameter` object in its :attr:`parameters` collection.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300444
Georg Brandle4717722012-08-14 09:45:28 +0200445 Signature objects are *immutable*. Use :meth:`Signature.replace` to make a
446 modified copy.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300447
448 .. attribute:: Signature.empty
449
450 A special class-level marker to specify absence of a return annotation.
451
452 .. attribute:: Signature.parameters
453
454 An ordered mapping of parameters' names to the corresponding
455 :class:`Parameter` objects.
456
457 .. attribute:: Signature.return_annotation
458
Georg Brandle4717722012-08-14 09:45:28 +0200459 The "return" annotation for the callable. If the callable has no "return"
460 annotation, this attribute is set to :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300461
462 .. method:: Signature.bind(*args, **kwargs)
463
Georg Brandle4717722012-08-14 09:45:28 +0200464 Create a mapping from positional and keyword arguments to parameters.
465 Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
466 signature, or raises a :exc:`TypeError`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300467
468 .. method:: Signature.bind_partial(*args, **kwargs)
469
Georg Brandle4717722012-08-14 09:45:28 +0200470 Works the same way as :meth:`Signature.bind`, but allows the omission of
471 some required arguments (mimics :func:`functools.partial` behavior.)
472 Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
473 passed arguments do not match the signature.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300474
Ezio Melotti8429b672012-09-14 06:35:09 +0300475 .. method:: Signature.replace(*[, parameters][, return_annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300476
Georg Brandle4717722012-08-14 09:45:28 +0200477 Create a new Signature instance based on the instance replace was invoked
478 on. It is possible to pass different ``parameters`` and/or
479 ``return_annotation`` to override the corresponding properties of the base
480 signature. To remove return_annotation from the copied Signature, pass in
481 :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300482
483 ::
484
485 >>> def test(a, b):
486 ... pass
487 >>> sig = signature(test)
488 >>> new_sig = sig.replace(return_annotation="new return anno")
489 >>> str(new_sig)
490 "(a, b) -> 'new return anno'"
491
492
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300493.. class:: Parameter
494
Georg Brandle4717722012-08-14 09:45:28 +0200495 Parameter objects are *immutable*. Instead of modifying a Parameter object,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300496 you can use :meth:`Parameter.replace` to create a modified copy.
497
498 .. attribute:: Parameter.empty
499
Georg Brandle4717722012-08-14 09:45:28 +0200500 A special class-level marker to specify absence of default values and
501 annotations.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300502
503 .. attribute:: Parameter.name
504
Georg Brandle4717722012-08-14 09:45:28 +0200505 The name of the parameter as a string. Must be a valid python identifier
506 name (with the exception of ``POSITIONAL_ONLY`` parameters, which can have
507 it set to ``None``).
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300508
509 .. attribute:: Parameter.default
510
Georg Brandle4717722012-08-14 09:45:28 +0200511 The default value for the parameter. If the parameter has no default
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300512 value, this attribute is set to :attr:`Parameter.empty`.
513
514 .. attribute:: Parameter.annotation
515
Georg Brandle4717722012-08-14 09:45:28 +0200516 The annotation for the parameter. If the parameter has no annotation,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300517 this attribute is set to :attr:`Parameter.empty`.
518
519 .. attribute:: Parameter.kind
520
Georg Brandle4717722012-08-14 09:45:28 +0200521 Describes how argument values are bound to the parameter. Possible values
522 (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300523
Georg Brandl44ea77b2013-03-28 13:28:44 +0100524 .. tabularcolumns:: |l|L|
525
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300526 +------------------------+----------------------------------------------+
527 | Name | Meaning |
528 +========================+==============================================+
529 | *POSITIONAL_ONLY* | Value must be supplied as a positional |
530 | | argument. |
531 | | |
532 | | Python has no explicit syntax for defining |
533 | | positional-only parameters, but many built-in|
534 | | and extension module functions (especially |
535 | | those that accept only one or two parameters)|
536 | | accept them. |
537 +------------------------+----------------------------------------------+
538 | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
539 | | positional argument (this is the standard |
540 | | binding behaviour for functions implemented |
541 | | in Python.) |
542 +------------------------+----------------------------------------------+
543 | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
544 | | bound to any other parameter. This |
545 | | corresponds to a ``*args`` parameter in a |
546 | | Python function definition. |
547 +------------------------+----------------------------------------------+
548 | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
549 | | Keyword only parameters are those which |
550 | | appear after a ``*`` or ``*args`` entry in a |
551 | | Python function definition. |
552 +------------------------+----------------------------------------------+
553 | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
554 | | to any other parameter. This corresponds to a|
555 | | ``**kwargs`` parameter in a Python function |
556 | | definition. |
557 +------------------------+----------------------------------------------+
558
Andrew Svetloveed18082012-08-13 18:23:54 +0300559 Example: print all keyword-only arguments without default values::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300560
561 >>> def foo(a, b, *, c, d=10):
562 ... pass
563
564 >>> sig = signature(foo)
565 >>> for param in sig.parameters.values():
566 ... if (param.kind == param.KEYWORD_ONLY and
567 ... param.default is param.empty):
568 ... print('Parameter:', param)
569 Parameter: c
570
Ezio Melotti8429b672012-09-14 06:35:09 +0300571 .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300572
Georg Brandle4717722012-08-14 09:45:28 +0200573 Create a new Parameter instance based on the instance replaced was invoked
574 on. To override a :class:`Parameter` attribute, pass the corresponding
575 argument. To remove a default value or/and an annotation from a
576 Parameter, pass :attr:`Parameter.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300577
578 ::
579
580 >>> from inspect import Parameter
581 >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
582 >>> str(param)
583 'foo=42'
584
585 >>> str(param.replace()) # Will create a shallow copy of 'param'
586 'foo=42'
587
588 >>> str(param.replace(default=Parameter.empty, annotation='spam'))
589 "foo:'spam'"
590
591
592.. class:: BoundArguments
593
594 Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
595 Holds the mapping of arguments to the function's parameters.
596
597 .. attribute:: BoundArguments.arguments
598
599 An ordered, mutable mapping (:class:`collections.OrderedDict`) of
Georg Brandle4717722012-08-14 09:45:28 +0200600 parameters' names to arguments' values. Contains only explicitly bound
601 arguments. Changes in :attr:`arguments` will reflect in :attr:`args` and
602 :attr:`kwargs`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300603
Georg Brandle4717722012-08-14 09:45:28 +0200604 Should be used in conjunction with :attr:`Signature.parameters` for any
605 argument processing purposes.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300606
607 .. note::
608
609 Arguments for which :meth:`Signature.bind` or
610 :meth:`Signature.bind_partial` relied on a default value are skipped.
Georg Brandle4717722012-08-14 09:45:28 +0200611 However, if needed, it is easy to include them.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300612
613 ::
614
615 >>> def foo(a, b=10):
616 ... pass
617
618 >>> sig = signature(foo)
619 >>> ba = sig.bind(5)
620
621 >>> ba.args, ba.kwargs
622 ((5,), {})
623
624 >>> for param in sig.parameters.values():
625 ... if param.name not in ba.arguments:
626 ... ba.arguments[param.name] = param.default
627
628 >>> ba.args, ba.kwargs
629 ((5, 10), {})
630
631
632 .. attribute:: BoundArguments.args
633
Georg Brandle4717722012-08-14 09:45:28 +0200634 A tuple of positional arguments values. Dynamically computed from the
635 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300636
637 .. attribute:: BoundArguments.kwargs
638
Georg Brandle4717722012-08-14 09:45:28 +0200639 A dict of keyword arguments values. Dynamically computed from the
640 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300641
Georg Brandle4717722012-08-14 09:45:28 +0200642 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
643 functions::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300644
645 def test(a, *, b):
646 ...
647
648 sig = signature(test)
649 ba = sig.bind(10, b=20)
650 test(*ba.args, **ba.kwargs)
651
652
Georg Brandle4717722012-08-14 09:45:28 +0200653.. seealso::
654
655 :pep:`362` - Function Signature Object.
656 The detailed specification, implementation details and examples.
657
658
Georg Brandl116aa622007-08-15 14:28:22 +0000659.. _inspect-classes-functions:
660
661Classes and functions
662---------------------
663
Georg Brandl3dd33882009-06-01 17:35:27 +0000664.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000665
666 Arrange the given list of classes into a hierarchy of nested lists. Where a
667 nested list appears, it contains classes derived from the class whose entry
668 immediately precedes the list. Each entry is a 2-tuple containing a class and a
669 tuple of its base classes. If the *unique* argument is true, exactly one entry
670 appears in the returned structure for each class in the given list. Otherwise,
671 classes using multiple inheritance and their descendants will appear multiple
672 times.
673
674
675.. function:: getargspec(func)
676
Georg Brandl82402752010-01-09 09:48:46 +0000677 Get the names and default values of a Python function's arguments. A
Georg Brandlb30f3302011-01-06 09:23:56 +0000678 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
679 returned. *args* is a list of the argument names. *varargs* and *keywords*
680 are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700681 tuple of default argument values or ``None`` if there are no default
682 arguments; if this tuple has *n* elements, they correspond to the last
683 *n* elements listed in *args*.
Georg Brandl138bcb52007-09-12 19:04:21 +0000684
685 .. deprecated:: 3.0
686 Use :func:`getfullargspec` instead, which provides information about
Benjamin Peterson3e8e9cc2008-11-12 21:26:46 +0000687 keyword-only arguments and annotations.
Georg Brandl138bcb52007-09-12 19:04:21 +0000688
689
690.. function:: getfullargspec(func)
691
Georg Brandl82402752010-01-09 09:48:46 +0000692 Get the names and default values of a Python function's arguments. A
693 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000694
Georg Brandl3dd33882009-06-01 17:35:27 +0000695 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
696 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000697
698 *args* is a list of the argument names. *varargs* and *varkw* are the names
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700699 of the ``*`` and ``**`` arguments or ``None``. *defaults* is an *n*-tuple
700 of the default values of the last *n* arguments, or ``None`` if there are no
701 default arguments. *kwonlyargs* is a list of
Georg Brandl138bcb52007-09-12 19:04:21 +0000702 keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
703 from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
704 names to annotations.
705
706 The first four items in the tuple correspond to :func:`getargspec`.
Georg Brandl116aa622007-08-15 14:28:22 +0000707
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300708 .. note::
709 Consider using the new :ref:`Signature Object <inspect-signature-object>`
710 interface, which provides a better way of introspecting functions.
711
Georg Brandl116aa622007-08-15 14:28:22 +0000712
713.. function:: getargvalues(frame)
714
Georg Brandl3dd33882009-06-01 17:35:27 +0000715 Get information about arguments passed into a particular frame. A
716 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000717 returned. *args* is a list of the argument names. *varargs* and *keywords*
718 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000719 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000720
721
Andrew Svetlov735d3172012-10-27 00:28:20 +0300722.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Georg Brandl116aa622007-08-15 14:28:22 +0000723
Michael Foord3af125a2012-04-21 18:22:28 +0100724 Format a pretty argument spec from the values returned by
725 :func:`getargspec` or :func:`getfullargspec`.
726
727 The first seven arguments are (``args``, ``varargs``, ``varkw``,
728 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``). The
729 other five arguments are the corresponding optional formatting functions
730 that are called to turn names and values into strings. The last argument
Andrew Svetlov735d3172012-10-27 00:28:20 +0300731 is an optional function to format the sequence of arguments. For example::
732
733 >>> from inspect import formatargspec, getfullargspec
734 >>> def f(a: int, b: float):
735 ... pass
736 ...
737 >>> formatargspec(*getfullargspec(f))
738 '(a: int, b: float)'
Georg Brandl116aa622007-08-15 14:28:22 +0000739
740
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000741.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000742
743 Format a pretty argument spec from the four values returned by
744 :func:`getargvalues`. The format\* arguments are the corresponding optional
745 formatting functions that are called to turn names and values into strings.
746
747
748.. function:: getmro(cls)
749
750 Return a tuple of class cls's base classes, including cls, in method resolution
751 order. No class appears more than once in this tuple. Note that the method
752 resolution order depends on cls's type. Unless a very peculiar user-defined
753 metatype is in use, cls will be the first element of the tuple.
754
755
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000756.. function:: getcallargs(func[, *args][, **kwds])
757
758 Bind the *args* and *kwds* to the argument names of the Python function or
759 method *func*, as if it was called with them. For bound methods, bind also the
760 first argument (typically named ``self``) to the associated instance. A dict
761 is returned, mapping the argument names (including the names of the ``*`` and
762 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
763 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
764 an exception because of incompatible signature, an exception of the same type
765 and the same or similar message is raised. For example::
766
767 >>> from inspect import getcallargs
768 >>> def f(a, b=1, *pos, **named):
769 ... pass
Andrew Svetlove939f382012-08-09 13:25:32 +0300770 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
771 True
772 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
773 True
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000774 >>> getcallargs(f)
775 Traceback (most recent call last):
776 ...
Andrew Svetlove939f382012-08-09 13:25:32 +0300777 TypeError: f() missing 1 required positional argument: 'a'
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000778
779 .. versionadded:: 3.2
780
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300781 .. note::
782 Consider using the new :meth:`Signature.bind` instead.
783
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000784
Nick Coghlan2f92e542012-06-23 19:39:55 +1000785.. function:: getclosurevars(func)
786
787 Get the mapping of external name references in a Python function or
788 method *func* to their current values. A
789 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
790 is returned. *nonlocals* maps referenced names to lexical closure
791 variables, *globals* to the function's module globals and *builtins* to
792 the builtins visible from the function body. *unbound* is the set of names
793 referenced in the function that could not be resolved at all given the
794 current module globals and builtins.
795
796 :exc:`TypeError` is raised if *func* is not a Python function or method.
797
798 .. versionadded:: 3.3
799
800
Nick Coghlane8c45d62013-07-28 20:00:01 +1000801.. function:: unwrap(func, *, stop=None)
802
803 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
804 attributes returning the last object in the chain.
805
806 *stop* is an optional callback accepting an object in the wrapper chain
807 as its sole argument that allows the unwrapping to be terminated early if
808 the callback returns a true value. If the callback never returns a true
809 value, the last object in the chain is returned as usual. For example,
810 :func:`signature` uses this to stop unwrapping if any object in the
811 chain has a ``__signature__`` attribute defined.
812
813 :exc:`ValueError` is raised if a cycle is encountered.
814
815 .. versionadded:: 3.4
816
817
Georg Brandl116aa622007-08-15 14:28:22 +0000818.. _inspect-stack:
819
820The interpreter stack
821---------------------
822
823When the following functions return "frame records," each record is a tuple of
824six items: the frame object, the filename, the line number of the current line,
825the function name, a list of lines of context from the source code, and the
826index of the current line within that list.
827
Georg Brandle720c0a2009-04-27 16:20:50 +0000828.. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000829
830 Keeping references to frame objects, as found in the first element of the frame
831 records these functions return, can cause your program to create reference
832 cycles. Once a reference cycle has been created, the lifespan of all objects
833 which can be accessed from the objects which form the cycle can become much
834 longer even if Python's optional cycle detector is enabled. If such cycles must
835 be created, it is important to ensure they are explicitly broken to avoid the
836 delayed destruction of objects and increased memory consumption which occurs.
837
838 Though the cycle detector will catch these, destruction of the frames (and local
839 variables) can be made deterministic by removing the cycle in a
840 :keyword:`finally` clause. This is also important if the cycle detector was
841 disabled when Python was compiled or using :func:`gc.disable`. For example::
842
843 def handle_stackframe_without_leak():
844 frame = inspect.currentframe()
845 try:
846 # do something with the frame
847 finally:
848 del frame
849
Antoine Pitrou58720d62013-08-05 23:26:40 +0200850 If you want to keep the frame around (for example to print a traceback
851 later), you can also break reference cycles by using the
852 :meth:`frame.clear` method.
853
Georg Brandl116aa622007-08-15 14:28:22 +0000854The optional *context* argument supported by most of these functions specifies
855the number of lines of context to return, which are centered around the current
856line.
857
858
Georg Brandl3dd33882009-06-01 17:35:27 +0000859.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000860
Georg Brandl48310cd2009-01-03 21:18:54 +0000861 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +0000862 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000863
864
Georg Brandl3dd33882009-06-01 17:35:27 +0000865.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000866
867 Get a list of frame records for a frame and all outer frames. These frames
868 represent the calls that lead to the creation of *frame*. The first entry in the
869 returned list represents *frame*; the last entry represents the outermost call
870 on *frame*'s stack.
871
872
Georg Brandl3dd33882009-06-01 17:35:27 +0000873.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000874
875 Get a list of frame records for a traceback's frame and all inner frames. These
876 frames represent calls made as a consequence of *frame*. The first entry in the
877 list represents *traceback*; the last entry represents where the exception was
878 raised.
879
880
881.. function:: currentframe()
882
883 Return the frame object for the caller's stack frame.
884
Georg Brandl495f7b52009-10-27 15:28:25 +0000885 .. impl-detail::
886
887 This function relies on Python stack frame support in the interpreter,
888 which isn't guaranteed to exist in all implementations of Python. If
889 running in an implementation without Python stack frame support this
890 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000891
Georg Brandl116aa622007-08-15 14:28:22 +0000892
Georg Brandl3dd33882009-06-01 17:35:27 +0000893.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000894
895 Return a list of frame records for the caller's stack. The first entry in the
896 returned list represents the caller; the last entry represents the outermost
897 call on the stack.
898
899
Georg Brandl3dd33882009-06-01 17:35:27 +0000900.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000901
902 Return a list of frame records for the stack between the current frame and the
903 frame in which an exception currently being handled was raised in. The first
904 entry in the list represents the caller; the last entry represents where the
905 exception was raised.
906
Michael Foord95fc51d2010-11-20 15:07:30 +0000907
908Fetching attributes statically
909------------------------------
910
911Both :func:`getattr` and :func:`hasattr` can trigger code execution when
912fetching or checking for the existence of attributes. Descriptors, like
913properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
914may be called.
915
916For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +0200917can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +0000918but avoids executing code when it fetches attributes.
919
920.. function:: getattr_static(obj, attr, default=None)
921
922 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +0200923 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +0000924
925 Note: this function may not be able to retrieve all attributes
926 that getattr can fetch (like dynamically created attributes)
927 and may find attributes that getattr can't (like descriptors
928 that raise AttributeError). It can also return descriptors objects
929 instead of instance members.
930
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300931 If the instance :attr:`~object.__dict__` is shadowed by another member (for
932 example a property) then this function will be unable to find instance
933 members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +0000934
Michael Foorddcebe0f2011-03-15 19:20:44 -0400935 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +0000936
Éric Araujo941afed2011-09-01 02:47:34 +0200937:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +0000938getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +0000939is returned instead of the underlying attribute.
940
941You can handle these with code like the following. Note that
942for arbitrary getset descriptors invoking these may trigger
943code execution::
944
945 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +0000946 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +0000947 __slots__ = ['foo']
948
949 slot_descriptor = type(_foo.foo)
950 getset_descriptor = type(type(open(__file__)).name)
951 wrapper_descriptor = type(str.__dict__['__add__'])
952 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
953
954 result = getattr_static(some_object, 'foo')
955 if type(result) in descriptor_types:
956 try:
957 result = result.__get__()
958 except AttributeError:
959 # descriptors can raise AttributeError to
960 # indicate there is no underlying value
961 # in which case the descriptor itself will
962 # have to do
963 pass
Nick Coghlane0f04652010-11-21 03:44:04 +0000964
Nick Coghlan2dad5ca2010-11-21 03:55:53 +0000965
Nick Coghlane0f04652010-11-21 03:44:04 +0000966Current State of a Generator
967----------------------------
968
969When implementing coroutine schedulers and for other advanced uses of
970generators, it is useful to determine whether a generator is currently
971executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +0000972terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +0000973generator to be determined easily.
974
975.. function:: getgeneratorstate(generator)
976
Raymond Hettinger48f3bd32010-12-16 00:30:53 +0000977 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +0000978
Raymond Hettinger48f3bd32010-12-16 00:30:53 +0000979 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +0000980 * GEN_CREATED: Waiting to start execution.
981 * GEN_RUNNING: Currently being executed by the interpreter.
982 * GEN_SUSPENDED: Currently suspended at a yield expression.
983 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +0000984
Nick Coghlan2dad5ca2010-11-21 03:55:53 +0000985 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +1000986
987The current internal state of the generator can also be queried. This is
988mostly useful for testing purposes, to ensure that internal state is being
989updated as expected:
990
991.. function:: getgeneratorlocals(generator)
992
993 Get the mapping of live local variables in *generator* to their current
994 values. A dictionary is returned that maps from variable names to values.
995 This is the equivalent of calling :func:`locals` in the body of the
996 generator, and all the same caveats apply.
997
998 If *generator* is a :term:`generator` with no currently associated frame,
999 then an empty dictionary is returned. :exc:`TypeError` is raised if
1000 *generator* is not a Python generator object.
1001
1002 .. impl-detail::
1003
1004 This function relies on the generator exposing a Python stack frame
1005 for introspection, which isn't guaranteed to be the case in all
1006 implementations of Python. In such cases, this function will always
1007 return an empty dictionary.
1008
1009 .. versionadded:: 3.3
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001010
1011
Nick Coghlan367df122013-10-27 01:57:34 +10001012.. _inspect-module-cli:
1013
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001014Command Line Interface
1015----------------------
1016
1017The :mod:`inspect` module also provides a basic introspection capability
1018from the command line.
1019
1020.. program:: inspect
1021
1022By default, accepts the name of a module and prints the source of that
1023module. A class or function within the module can be printed instead by
1024appended a colon and the qualified name of the target object.
1025
1026.. cmdoption:: --details
1027
1028 Print information about the specified object rather than the source code