blob: 3d2132fd86426383a8fa6aad63c62a73e436c0ac [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 |
Yury Selivanovea2d66e2014-01-27 14:26:28 -050072| | | values for positional or |
73| | | keyword parameters |
74+-----------+-----------------+---------------------------+
75| | __kwdefaults__ | mapping of any default |
76| | | values for keyword-only |
77| | | parameters |
Georg Brandl55ac8f02007-09-01 13:51:09 +000078+-----------+-----------------+---------------------------+
79| | __globals__ | global namespace in which |
80| | | this function was defined |
81+-----------+-----------------+---------------------------+
82| traceback | tb_frame | frame object at this |
83| | | level |
84+-----------+-----------------+---------------------------+
85| | tb_lasti | index of last attempted |
86| | | instruction in bytecode |
87+-----------+-----------------+---------------------------+
88| | tb_lineno | current line number in |
89| | | Python source code |
90+-----------+-----------------+---------------------------+
91| | tb_next | next inner traceback |
92| | | object (called by this |
93| | | level) |
94+-----------+-----------------+---------------------------+
95| frame | f_back | next outer frame object |
96| | | (this frame's caller) |
97+-----------+-----------------+---------------------------+
Georg Brandlc4a55fc2010-02-06 18:46:57 +000098| | f_builtins | builtins namespace seen |
Georg Brandl55ac8f02007-09-01 13:51:09 +000099| | | by this frame |
100+-----------+-----------------+---------------------------+
101| | f_code | code object being |
102| | | executed in this frame |
103+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000104| | f_globals | global namespace seen by |
105| | | this frame |
106+-----------+-----------------+---------------------------+
107| | f_lasti | index of last attempted |
108| | | instruction in bytecode |
109+-----------+-----------------+---------------------------+
110| | f_lineno | current line number in |
111| | | Python source code |
112+-----------+-----------------+---------------------------+
113| | f_locals | local namespace seen by |
114| | | this frame |
115+-----------+-----------------+---------------------------+
116| | f_restricted | 0 or 1 if frame is in |
117| | | restricted execution mode |
118+-----------+-----------------+---------------------------+
119| | f_trace | tracing function for this |
120| | | frame, or ``None`` |
121+-----------+-----------------+---------------------------+
122| code | co_argcount | number of arguments (not |
123| | | including \* or \*\* |
124| | | args) |
125+-----------+-----------------+---------------------------+
126| | co_code | string of raw compiled |
127| | | bytecode |
128+-----------+-----------------+---------------------------+
129| | co_consts | tuple of constants used |
130| | | in the bytecode |
131+-----------+-----------------+---------------------------+
132| | co_filename | name of file in which |
133| | | this code object was |
134| | | created |
135+-----------+-----------------+---------------------------+
136| | co_firstlineno | number of first line in |
137| | | Python source code |
138+-----------+-----------------+---------------------------+
139| | co_flags | bitmap: 1=optimized ``|`` |
140| | | 2=newlocals ``|`` 4=\*arg |
141| | | ``|`` 8=\*\*arg |
142+-----------+-----------------+---------------------------+
143| | co_lnotab | encoded mapping of line |
144| | | numbers to bytecode |
145| | | indices |
146+-----------+-----------------+---------------------------+
147| | co_name | name with which this code |
148| | | object was defined |
149+-----------+-----------------+---------------------------+
150| | co_names | tuple of names of local |
151| | | variables |
152+-----------+-----------------+---------------------------+
153| | co_nlocals | number of local variables |
154+-----------+-----------------+---------------------------+
155| | co_stacksize | virtual machine stack |
156| | | space required |
157+-----------+-----------------+---------------------------+
158| | co_varnames | tuple of names of |
159| | | arguments and local |
160| | | variables |
161+-----------+-----------------+---------------------------+
Victor Stinner40ee3012014-06-16 15:59:28 +0200162| generator | __name__ | name |
163+-----------+-----------------+---------------------------+
164| | __qualname__ | qualified name |
165+-----------+-----------------+---------------------------+
166| | gi_frame | frame |
167+-----------+-----------------+---------------------------+
168| | gi_running | is the generator running? |
169+-----------+-----------------+---------------------------+
170| | gi_code | code |
171+-----------+-----------------+---------------------------+
Georg Brandl55ac8f02007-09-01 13:51:09 +0000172| builtin | __doc__ | documentation string |
173+-----------+-----------------+---------------------------+
174| | __name__ | original name of this |
175| | | function or method |
176+-----------+-----------------+---------------------------+
177| | __self__ | instance to which a |
178| | | method is bound, or |
179| | | ``None`` |
180+-----------+-----------------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000181
Victor Stinner40ee3012014-06-16 15:59:28 +0200182.. versionchanged:: 3.5
183
Victor Stinner4a74a9a2014-06-16 16:25:22 +0200184 Add ``__qualname__`` attribute to generators. The ``__name__`` attribute of
185 generators is now set from the function name, instead of the code name, and
186 it can now be modified.
Victor Stinner40ee3012014-06-16 15:59:28 +0200187
Georg Brandl116aa622007-08-15 14:28:22 +0000188
189.. function:: getmembers(object[, predicate])
190
191 Return all the members of an object in a list of (name, value) pairs sorted by
192 name. If the optional *predicate* argument is supplied, only members for which
193 the predicate returns a true value are included.
194
Christian Heimes7f044312008-01-06 17:05:40 +0000195 .. note::
196
Ethan Furman63c141c2013-10-18 00:27:39 -0700197 :func:`getmembers` will only return class attributes defined in the
198 metaclass when the argument is a class and those attributes have been
199 listed in the metaclass' custom :meth:`__dir__`.
Christian Heimes7f044312008-01-06 17:05:40 +0000200
Georg Brandl116aa622007-08-15 14:28:22 +0000201
202.. function:: getmoduleinfo(path)
203
Georg Brandlb30f3302011-01-06 09:23:56 +0000204 Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode, module_type)``
205 of values that describe how Python will interpret the file identified by
206 *path* if it is a module, or ``None`` if it would not be identified as a
207 module. In that tuple, *name* is the name of the module without the name of
208 any enclosing package, *suffix* is the trailing part of the file name (which
209 may not be a dot-delimited extension), *mode* is the :func:`open` mode that
210 would be used (``'r'`` or ``'rb'``), and *module_type* is an integer giving
211 the type of the module. *module_type* will have a value which can be
212 compared to the constants defined in the :mod:`imp` module; see the
213 documentation for that module for more information on module types.
Georg Brandl116aa622007-08-15 14:28:22 +0000214
Brett Cannoncb66eb02012-05-11 12:58:42 -0400215 .. deprecated:: 3.3
216 You may check the file path's suffix against the supported suffixes
217 listed in :mod:`importlib.machinery` to infer the same information.
218
Georg Brandl116aa622007-08-15 14:28:22 +0000219
220.. function:: getmodulename(path)
221
222 Return the name of the module named by the file *path*, without including the
Nick Coghlan76e07702012-07-18 23:14:57 +1000223 names of enclosing packages. The file extension is checked against all of
224 the entries in :func:`importlib.machinery.all_suffixes`. If it matches,
225 the final path component is returned with the extension removed.
226 Otherwise, ``None`` is returned.
227
228 Note that this function *only* returns a meaningful name for actual
229 Python modules - paths that potentially refer to Python packages will
230 still return ``None``.
231
232 .. versionchanged:: 3.3
233 This function is now based directly on :mod:`importlib` rather than the
234 deprecated :func:`getmoduleinfo`.
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236
237.. function:: ismodule(object)
238
239 Return true if the object is a module.
240
241
242.. function:: isclass(object)
243
Georg Brandl39cadc32010-10-15 16:53:24 +0000244 Return true if the object is a class, whether built-in or created in Python
245 code.
Georg Brandl116aa622007-08-15 14:28:22 +0000246
247
248.. function:: ismethod(object)
249
Georg Brandl39cadc32010-10-15 16:53:24 +0000250 Return true if the object is a bound method written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000251
252
253.. function:: isfunction(object)
254
Georg Brandl39cadc32010-10-15 16:53:24 +0000255 Return true if the object is a Python function, which includes functions
256 created by a :term:`lambda` expression.
Georg Brandl116aa622007-08-15 14:28:22 +0000257
258
Christian Heimes7131fd92008-02-19 14:21:46 +0000259.. function:: isgeneratorfunction(object)
260
261 Return true if the object is a Python generator function.
262
263
264.. function:: isgenerator(object)
265
266 Return true if the object is a generator.
267
268
Georg Brandl116aa622007-08-15 14:28:22 +0000269.. function:: istraceback(object)
270
271 Return true if the object is a traceback.
272
273
274.. function:: isframe(object)
275
276 Return true if the object is a frame.
277
278
279.. function:: iscode(object)
280
281 Return true if the object is a code.
282
283
284.. function:: isbuiltin(object)
285
Georg Brandl39cadc32010-10-15 16:53:24 +0000286 Return true if the object is a built-in function or a bound built-in method.
Georg Brandl116aa622007-08-15 14:28:22 +0000287
288
289.. function:: isroutine(object)
290
291 Return true if the object is a user-defined or built-in function or method.
292
Georg Brandl39cadc32010-10-15 16:53:24 +0000293
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000294.. function:: isabstract(object)
295
296 Return true if the object is an abstract base class.
297
Georg Brandl116aa622007-08-15 14:28:22 +0000298
299.. function:: ismethoddescriptor(object)
300
Georg Brandl39cadc32010-10-15 16:53:24 +0000301 Return true if the object is a method descriptor, but not if
302 :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
303 are true.
Georg Brandl116aa622007-08-15 14:28:22 +0000304
Georg Brandle6bcc912008-05-12 18:05:20 +0000305 This, for example, is true of ``int.__add__``. An object passing this test
306 has a :attr:`__get__` attribute but not a :attr:`__set__` attribute, but
307 beyond that the set of attributes varies. :attr:`__name__` is usually
308 sensible, and :attr:`__doc__` often is.
Georg Brandl116aa622007-08-15 14:28:22 +0000309
Georg Brandl9afde1c2007-11-01 20:32:30 +0000310 Methods implemented via descriptors that also pass one of the other tests
311 return false from the :func:`ismethoddescriptor` test, simply because the
312 other tests promise more -- you can, e.g., count on having the
Christian Heimesff737952007-11-27 10:40:20 +0000313 :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`.
Georg Brandl116aa622007-08-15 14:28:22 +0000314
315
316.. function:: isdatadescriptor(object)
317
318 Return true if the object is a data descriptor.
319
Georg Brandl9afde1c2007-11-01 20:32:30 +0000320 Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute.
321 Examples are properties (defined in Python), getsets, and members. The
322 latter two are defined in C and there are more specific tests available for
323 those types, which is robust across Python implementations. Typically, data
324 descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes
325 (properties, getsets, and members have both of these attributes), but this is
326 not guaranteed.
Georg Brandl116aa622007-08-15 14:28:22 +0000327
Georg Brandl116aa622007-08-15 14:28:22 +0000328
329.. function:: isgetsetdescriptor(object)
330
331 Return true if the object is a getset descriptor.
332
Georg Brandl495f7b52009-10-27 15:28:25 +0000333 .. impl-detail::
334
335 getsets are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000336 :c:type:`PyGetSetDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000337 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000338
Georg Brandl116aa622007-08-15 14:28:22 +0000339
340.. function:: ismemberdescriptor(object)
341
342 Return true if the object is a member descriptor.
343
Georg Brandl495f7b52009-10-27 15:28:25 +0000344 .. impl-detail::
345
346 Member descriptors are attributes defined in extension modules via
Georg Brandl60203b42010-10-06 10:11:56 +0000347 :c:type:`PyMemberDef` structures. For Python implementations without such
Georg Brandl495f7b52009-10-27 15:28:25 +0000348 types, this method will always return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000349
Georg Brandl116aa622007-08-15 14:28:22 +0000350
351.. _inspect-source:
352
353Retrieving source code
354----------------------
355
Georg Brandl116aa622007-08-15 14:28:22 +0000356.. function:: getdoc(object)
357
Georg Brandl0c77a822008-06-10 16:37:50 +0000358 Get the documentation string for an object, cleaned up with :func:`cleandoc`.
Georg Brandl116aa622007-08-15 14:28:22 +0000359
360
361.. function:: getcomments(object)
362
363 Return in a single string any lines of comments immediately preceding the
364 object's source code (for a class, function, or method), or at the top of the
365 Python source file (if the object is a module).
366
367
368.. function:: getfile(object)
369
370 Return the name of the (text or binary) file in which an object was defined.
371 This will fail with a :exc:`TypeError` if the object is a built-in module,
372 class, or function.
373
374
375.. function:: getmodule(object)
376
377 Try to guess which module an object was defined in.
378
379
380.. function:: getsourcefile(object)
381
382 Return the name of the Python source file in which an object was defined. This
383 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
384 function.
385
386
387.. function:: getsourcelines(object)
388
389 Return a list of source lines and starting line number for an object. The
390 argument may be a module, class, method, function, traceback, frame, or code
391 object. The source code is returned as a list of the lines corresponding to the
392 object and the line number indicates where in the original source file the first
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200393 line of code was found. An :exc:`OSError` is raised if the source code cannot
Georg Brandl116aa622007-08-15 14:28:22 +0000394 be retrieved.
395
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200396 .. versionchanged:: 3.3
397 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
398 former.
399
Georg Brandl116aa622007-08-15 14:28:22 +0000400
401.. function:: getsource(object)
402
403 Return the text of the source code for an object. The argument may be a module,
404 class, method, function, traceback, frame, or code object. The source code is
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200405 returned as a single string. An :exc:`OSError` is raised if the source code
Georg Brandl116aa622007-08-15 14:28:22 +0000406 cannot be retrieved.
407
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200408 .. versionchanged:: 3.3
409 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
410 former.
411
Georg Brandl116aa622007-08-15 14:28:22 +0000412
Georg Brandl0c77a822008-06-10 16:37:50 +0000413.. function:: cleandoc(doc)
414
415 Clean up indentation from docstrings that are indented to line up with blocks
416 of code. Any whitespace that can be uniformly removed from the second line
417 onwards is removed. Also, all tabs are expanded to spaces.
418
Georg Brandl0c77a822008-06-10 16:37:50 +0000419
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300420.. _inspect-signature-object:
421
Georg Brandle4717722012-08-14 09:45:28 +0200422Introspecting callables with the Signature object
423-------------------------------------------------
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300424
425.. versionadded:: 3.3
426
Georg Brandle4717722012-08-14 09:45:28 +0200427The Signature object represents the call signature of a callable object and its
428return annotation. To retrieve a Signature object, use the :func:`signature`
429function.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300430
431.. function:: signature(callable)
432
Georg Brandle4717722012-08-14 09:45:28 +0200433 Return a :class:`Signature` object for the given ``callable``::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300434
435 >>> from inspect import signature
436 >>> def foo(a, *, b:int, **kwargs):
437 ... pass
438
439 >>> sig = signature(foo)
440
441 >>> str(sig)
442 '(a, *, b:int, **kwargs)'
443
444 >>> str(sig.parameters['b'])
445 'b:int'
446
447 >>> sig.parameters['b'].annotation
448 <class 'int'>
449
Georg Brandle4717722012-08-14 09:45:28 +0200450 Accepts a wide range of python callables, from plain functions and classes to
451 :func:`functools.partial` objects.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300452
Larry Hastings5c661892014-01-24 06:17:25 -0800453 Raises :exc:`ValueError` if no signature can be provided, and
454 :exc:`TypeError` if that type of object is not supported.
455
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300456 .. note::
457
Georg Brandle4717722012-08-14 09:45:28 +0200458 Some callables may not be introspectable in certain implementations of
Yury Selivanovd71e52f2014-01-30 00:22:57 -0500459 Python. For example, in CPython, some built-in functions defined in
460 C provide no metadata about their arguments.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300461
462
Yury Selivanov78356892014-01-30 00:10:54 -0500463.. class:: Signature(parameters=None, \*, return_annotation=Signature.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300464
Georg Brandle4717722012-08-14 09:45:28 +0200465 A Signature object represents the call signature of a function and its return
466 annotation. For each parameter accepted by the function it stores a
467 :class:`Parameter` object in its :attr:`parameters` collection.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300468
Yury Selivanov78356892014-01-30 00:10:54 -0500469 The optional *parameters* argument is a sequence of :class:`Parameter`
470 objects, which is validated to check that there are no parameters with
471 duplicate names, and that the parameters are in the right order, i.e.
472 positional-only first, then positional-or-keyword, and that parameters with
473 defaults follow parameters without defaults.
474
475 The optional *return_annotation* argument, can be an arbitrary Python object,
476 is the "return" annotation of the callable.
477
Georg Brandle4717722012-08-14 09:45:28 +0200478 Signature objects are *immutable*. Use :meth:`Signature.replace` to make a
479 modified copy.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300480
Yury Selivanov67d727e2014-03-29 13:24:14 -0400481 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400482 Signature objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400483
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300484 .. attribute:: Signature.empty
485
486 A special class-level marker to specify absence of a return annotation.
487
488 .. attribute:: Signature.parameters
489
490 An ordered mapping of parameters' names to the corresponding
491 :class:`Parameter` objects.
492
493 .. attribute:: Signature.return_annotation
494
Georg Brandle4717722012-08-14 09:45:28 +0200495 The "return" annotation for the callable. If the callable has no "return"
496 annotation, this attribute is set to :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300497
498 .. method:: Signature.bind(*args, **kwargs)
499
Georg Brandle4717722012-08-14 09:45:28 +0200500 Create a mapping from positional and keyword arguments to parameters.
501 Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
502 signature, or raises a :exc:`TypeError`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300503
504 .. method:: Signature.bind_partial(*args, **kwargs)
505
Georg Brandle4717722012-08-14 09:45:28 +0200506 Works the same way as :meth:`Signature.bind`, but allows the omission of
507 some required arguments (mimics :func:`functools.partial` behavior.)
508 Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
509 passed arguments do not match the signature.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300510
Ezio Melotti8429b672012-09-14 06:35:09 +0300511 .. method:: Signature.replace(*[, parameters][, return_annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300512
Georg Brandle4717722012-08-14 09:45:28 +0200513 Create a new Signature instance based on the instance replace was invoked
514 on. It is possible to pass different ``parameters`` and/or
515 ``return_annotation`` to override the corresponding properties of the base
516 signature. To remove return_annotation from the copied Signature, pass in
517 :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300518
519 ::
520
521 >>> def test(a, b):
522 ... pass
523 >>> sig = signature(test)
524 >>> new_sig = sig.replace(return_annotation="new return anno")
525 >>> str(new_sig)
526 "(a, b) -> 'new return anno'"
527
Yury Selivanov232b9342014-03-29 13:18:30 -0400528 .. classmethod:: Signature.from_callable(obj)
Yury Selivanovda396452014-03-27 12:09:24 -0400529
530 Return a :class:`Signature` (or its subclass) object for a given callable
531 ``obj``. This method simplifies subclassing of :class:`Signature`:
532
533 ::
534
535 class MySignature(Signature):
536 pass
537 sig = MySignature.from_callable(min)
538 assert isinstance(sig, MySignature)
539
Yury Selivanov232b9342014-03-29 13:18:30 -0400540 .. versionadded:: 3.5
541
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300542
Yury Selivanov78356892014-01-30 00:10:54 -0500543.. class:: Parameter(name, kind, \*, default=Parameter.empty, annotation=Parameter.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300544
Georg Brandle4717722012-08-14 09:45:28 +0200545 Parameter objects are *immutable*. Instead of modifying a Parameter object,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300546 you can use :meth:`Parameter.replace` to create a modified copy.
547
Yury Selivanov67d727e2014-03-29 13:24:14 -0400548 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400549 Parameter objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400550
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300551 .. attribute:: Parameter.empty
552
Georg Brandle4717722012-08-14 09:45:28 +0200553 A special class-level marker to specify absence of default values and
554 annotations.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300555
556 .. attribute:: Parameter.name
557
Yury Selivanov2393dca2014-01-27 15:07:58 -0500558 The name of the parameter as a string. The name must be a valid
559 Python identifier.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300560
561 .. attribute:: Parameter.default
562
Georg Brandle4717722012-08-14 09:45:28 +0200563 The default value for the parameter. If the parameter has no default
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300564 value, this attribute is set to :attr:`Parameter.empty`.
565
566 .. attribute:: Parameter.annotation
567
Georg Brandle4717722012-08-14 09:45:28 +0200568 The annotation for the parameter. If the parameter has no annotation,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300569 this attribute is set to :attr:`Parameter.empty`.
570
571 .. attribute:: Parameter.kind
572
Georg Brandle4717722012-08-14 09:45:28 +0200573 Describes how argument values are bound to the parameter. Possible values
574 (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300575
Georg Brandl44ea77b2013-03-28 13:28:44 +0100576 .. tabularcolumns:: |l|L|
577
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300578 +------------------------+----------------------------------------------+
579 | Name | Meaning |
580 +========================+==============================================+
581 | *POSITIONAL_ONLY* | Value must be supplied as a positional |
582 | | argument. |
583 | | |
584 | | Python has no explicit syntax for defining |
585 | | positional-only parameters, but many built-in|
586 | | and extension module functions (especially |
587 | | those that accept only one or two parameters)|
588 | | accept them. |
589 +------------------------+----------------------------------------------+
590 | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
591 | | positional argument (this is the standard |
592 | | binding behaviour for functions implemented |
593 | | in Python.) |
594 +------------------------+----------------------------------------------+
595 | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
596 | | bound to any other parameter. This |
597 | | corresponds to a ``*args`` parameter in a |
598 | | Python function definition. |
599 +------------------------+----------------------------------------------+
600 | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
601 | | Keyword only parameters are those which |
602 | | appear after a ``*`` or ``*args`` entry in a |
603 | | Python function definition. |
604 +------------------------+----------------------------------------------+
605 | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
606 | | to any other parameter. This corresponds to a|
607 | | ``**kwargs`` parameter in a Python function |
608 | | definition. |
609 +------------------------+----------------------------------------------+
610
Andrew Svetloveed18082012-08-13 18:23:54 +0300611 Example: print all keyword-only arguments without default values::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300612
613 >>> def foo(a, b, *, c, d=10):
614 ... pass
615
616 >>> sig = signature(foo)
617 >>> for param in sig.parameters.values():
618 ... if (param.kind == param.KEYWORD_ONLY and
619 ... param.default is param.empty):
620 ... print('Parameter:', param)
621 Parameter: c
622
Ezio Melotti8429b672012-09-14 06:35:09 +0300623 .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300624
Georg Brandle4717722012-08-14 09:45:28 +0200625 Create a new Parameter instance based on the instance replaced was invoked
626 on. To override a :class:`Parameter` attribute, pass the corresponding
627 argument. To remove a default value or/and an annotation from a
628 Parameter, pass :attr:`Parameter.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300629
630 ::
631
632 >>> from inspect import Parameter
633 >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
634 >>> str(param)
635 'foo=42'
636
637 >>> str(param.replace()) # Will create a shallow copy of 'param'
638 'foo=42'
639
640 >>> str(param.replace(default=Parameter.empty, annotation='spam'))
641 "foo:'spam'"
642
Yury Selivanov2393dca2014-01-27 15:07:58 -0500643 .. versionchanged:: 3.4
644 In Python 3.3 Parameter objects were allowed to have ``name`` set
645 to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``.
646 This is no longer permitted.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300647
648.. class:: BoundArguments
649
650 Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
651 Holds the mapping of arguments to the function's parameters.
652
653 .. attribute:: BoundArguments.arguments
654
655 An ordered, mutable mapping (:class:`collections.OrderedDict`) of
Georg Brandle4717722012-08-14 09:45:28 +0200656 parameters' names to arguments' values. Contains only explicitly bound
657 arguments. Changes in :attr:`arguments` will reflect in :attr:`args` and
658 :attr:`kwargs`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300659
Georg Brandle4717722012-08-14 09:45:28 +0200660 Should be used in conjunction with :attr:`Signature.parameters` for any
661 argument processing purposes.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300662
663 .. note::
664
665 Arguments for which :meth:`Signature.bind` or
666 :meth:`Signature.bind_partial` relied on a default value are skipped.
Georg Brandle4717722012-08-14 09:45:28 +0200667 However, if needed, it is easy to include them.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300668
669 ::
670
671 >>> def foo(a, b=10):
672 ... pass
673
674 >>> sig = signature(foo)
675 >>> ba = sig.bind(5)
676
677 >>> ba.args, ba.kwargs
678 ((5,), {})
679
680 >>> for param in sig.parameters.values():
Yury Selivanoved648a32014-12-04 22:48:47 -0500681 ... if (param.name not in ba.arguments
682 ... and param.default is not param.empty):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300683 ... ba.arguments[param.name] = param.default
684
685 >>> ba.args, ba.kwargs
686 ((5, 10), {})
687
688
689 .. attribute:: BoundArguments.args
690
Georg Brandle4717722012-08-14 09:45:28 +0200691 A tuple of positional arguments values. Dynamically computed from the
692 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300693
694 .. attribute:: BoundArguments.kwargs
695
Georg Brandle4717722012-08-14 09:45:28 +0200696 A dict of keyword arguments values. Dynamically computed from the
697 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300698
Georg Brandle4717722012-08-14 09:45:28 +0200699 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
700 functions::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300701
702 def test(a, *, b):
703 ...
704
705 sig = signature(test)
706 ba = sig.bind(10, b=20)
707 test(*ba.args, **ba.kwargs)
708
709
Georg Brandle4717722012-08-14 09:45:28 +0200710.. seealso::
711
712 :pep:`362` - Function Signature Object.
713 The detailed specification, implementation details and examples.
714
715
Georg Brandl116aa622007-08-15 14:28:22 +0000716.. _inspect-classes-functions:
717
718Classes and functions
719---------------------
720
Georg Brandl3dd33882009-06-01 17:35:27 +0000721.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000722
723 Arrange the given list of classes into a hierarchy of nested lists. Where a
724 nested list appears, it contains classes derived from the class whose entry
725 immediately precedes the list. Each entry is a 2-tuple containing a class and a
726 tuple of its base classes. If the *unique* argument is true, exactly one entry
727 appears in the returned structure for each class in the given list. Otherwise,
728 classes using multiple inheritance and their descendants will appear multiple
729 times.
730
731
732.. function:: getargspec(func)
733
Georg Brandl82402752010-01-09 09:48:46 +0000734 Get the names and default values of a Python function's arguments. A
Georg Brandlb30f3302011-01-06 09:23:56 +0000735 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
736 returned. *args* is a list of the argument names. *varargs* and *keywords*
737 are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700738 tuple of default argument values or ``None`` if there are no default
739 arguments; if this tuple has *n* elements, they correspond to the last
740 *n* elements listed in *args*.
Georg Brandl138bcb52007-09-12 19:04:21 +0000741
742 .. deprecated:: 3.0
743 Use :func:`getfullargspec` instead, which provides information about
Benjamin Peterson3e8e9cc2008-11-12 21:26:46 +0000744 keyword-only arguments and annotations.
Georg Brandl138bcb52007-09-12 19:04:21 +0000745
746
747.. function:: getfullargspec(func)
748
Georg Brandl82402752010-01-09 09:48:46 +0000749 Get the names and default values of a Python function's arguments. A
750 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000751
Georg Brandl3dd33882009-06-01 17:35:27 +0000752 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
753 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000754
755 *args* is a list of the argument names. *varargs* and *varkw* are the names
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700756 of the ``*`` and ``**`` arguments or ``None``. *defaults* is an *n*-tuple
757 of the default values of the last *n* arguments, or ``None`` if there are no
758 default arguments. *kwonlyargs* is a list of
Georg Brandl138bcb52007-09-12 19:04:21 +0000759 keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
760 from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
761 names to annotations.
762
763 The first four items in the tuple correspond to :func:`getargspec`.
Georg Brandl116aa622007-08-15 14:28:22 +0000764
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300765 .. note::
766 Consider using the new :ref:`Signature Object <inspect-signature-object>`
767 interface, which provides a better way of introspecting functions.
768
Nick Coghlan16355782014-03-08 16:36:37 +1000769 .. versionchanged:: 3.4
770 This function is now based on :func:`signature`, but still ignores
771 ``__wrapped__`` attributes and includes the already bound first
772 parameter in the signature output for bound methods.
773
Georg Brandl116aa622007-08-15 14:28:22 +0000774
775.. function:: getargvalues(frame)
776
Georg Brandl3dd33882009-06-01 17:35:27 +0000777 Get information about arguments passed into a particular frame. A
778 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000779 returned. *args* is a list of the argument names. *varargs* and *keywords*
780 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000781 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000782
783
Andrew Svetlov735d3172012-10-27 00:28:20 +0300784.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Georg Brandl116aa622007-08-15 14:28:22 +0000785
Michael Foord3af125a2012-04-21 18:22:28 +0100786 Format a pretty argument spec from the values returned by
787 :func:`getargspec` or :func:`getfullargspec`.
788
789 The first seven arguments are (``args``, ``varargs``, ``varkw``,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100790 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
Andrew Svetlov735d3172012-10-27 00:28:20 +0300791
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100792 The other six arguments are functions that are called to turn argument names,
793 ``*`` argument name, ``**`` argument name, default values, return annotation
794 and individual annotations into strings, respectively.
795
796 For example:
797
798 >>> from inspect import formatargspec, getfullargspec
799 >>> def f(a: int, b: float):
800 ... pass
801 ...
802 >>> formatargspec(*getfullargspec(f))
803 '(a: int, b: float)'
Georg Brandl116aa622007-08-15 14:28:22 +0000804
805
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000806.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000807
808 Format a pretty argument spec from the four values returned by
809 :func:`getargvalues`. The format\* arguments are the corresponding optional
810 formatting functions that are called to turn names and values into strings.
811
812
813.. function:: getmro(cls)
814
815 Return a tuple of class cls's base classes, including cls, in method resolution
816 order. No class appears more than once in this tuple. Note that the method
817 resolution order depends on cls's type. Unless a very peculiar user-defined
818 metatype is in use, cls will be the first element of the tuple.
819
820
Benjamin Peterson3a990c62014-01-02 12:22:30 -0600821.. function:: getcallargs(func, *args, **kwds)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000822
823 Bind the *args* and *kwds* to the argument names of the Python function or
824 method *func*, as if it was called with them. For bound methods, bind also the
825 first argument (typically named ``self``) to the associated instance. A dict
826 is returned, mapping the argument names (including the names of the ``*`` and
827 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
828 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
829 an exception because of incompatible signature, an exception of the same type
830 and the same or similar message is raised. For example::
831
832 >>> from inspect import getcallargs
833 >>> def f(a, b=1, *pos, **named):
834 ... pass
Andrew Svetlove939f382012-08-09 13:25:32 +0300835 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
836 True
837 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
838 True
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000839 >>> getcallargs(f)
840 Traceback (most recent call last):
841 ...
Andrew Svetlove939f382012-08-09 13:25:32 +0300842 TypeError: f() missing 1 required positional argument: 'a'
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000843
844 .. versionadded:: 3.2
845
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300846 .. note::
847 Consider using the new :meth:`Signature.bind` instead.
848
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000849
Nick Coghlan2f92e542012-06-23 19:39:55 +1000850.. function:: getclosurevars(func)
851
852 Get the mapping of external name references in a Python function or
853 method *func* to their current values. A
854 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
855 is returned. *nonlocals* maps referenced names to lexical closure
856 variables, *globals* to the function's module globals and *builtins* to
857 the builtins visible from the function body. *unbound* is the set of names
858 referenced in the function that could not be resolved at all given the
859 current module globals and builtins.
860
861 :exc:`TypeError` is raised if *func* is not a Python function or method.
862
863 .. versionadded:: 3.3
864
865
Nick Coghlane8c45d62013-07-28 20:00:01 +1000866.. function:: unwrap(func, *, stop=None)
867
868 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
869 attributes returning the last object in the chain.
870
871 *stop* is an optional callback accepting an object in the wrapper chain
872 as its sole argument that allows the unwrapping to be terminated early if
873 the callback returns a true value. If the callback never returns a true
874 value, the last object in the chain is returned as usual. For example,
875 :func:`signature` uses this to stop unwrapping if any object in the
876 chain has a ``__signature__`` attribute defined.
877
878 :exc:`ValueError` is raised if a cycle is encountered.
879
880 .. versionadded:: 3.4
881
882
Georg Brandl116aa622007-08-15 14:28:22 +0000883.. _inspect-stack:
884
885The interpreter stack
886---------------------
887
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400888When the following functions return "frame records," each record is a
889:term:`named tuple`
890``FrameInfo(frame, filename, lineno, function, code_context, index)``.
891The tuple contains the frame object, the filename, the line number of the
892current line,
Georg Brandl116aa622007-08-15 14:28:22 +0000893the function name, a list of lines of context from the source code, and the
894index of the current line within that list.
895
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400896.. versionchanged:: 3.5
897 Return a named tuple instead of a tuple.
898
Georg Brandle720c0a2009-04-27 16:20:50 +0000899.. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000900
901 Keeping references to frame objects, as found in the first element of the frame
902 records these functions return, can cause your program to create reference
903 cycles. Once a reference cycle has been created, the lifespan of all objects
904 which can be accessed from the objects which form the cycle can become much
905 longer even if Python's optional cycle detector is enabled. If such cycles must
906 be created, it is important to ensure they are explicitly broken to avoid the
907 delayed destruction of objects and increased memory consumption which occurs.
908
909 Though the cycle detector will catch these, destruction of the frames (and local
910 variables) can be made deterministic by removing the cycle in a
911 :keyword:`finally` clause. This is also important if the cycle detector was
912 disabled when Python was compiled or using :func:`gc.disable`. For example::
913
914 def handle_stackframe_without_leak():
915 frame = inspect.currentframe()
916 try:
917 # do something with the frame
918 finally:
919 del frame
920
Antoine Pitrou58720d62013-08-05 23:26:40 +0200921 If you want to keep the frame around (for example to print a traceback
922 later), you can also break reference cycles by using the
923 :meth:`frame.clear` method.
924
Georg Brandl116aa622007-08-15 14:28:22 +0000925The optional *context* argument supported by most of these functions specifies
926the number of lines of context to return, which are centered around the current
927line.
928
929
Georg Brandl3dd33882009-06-01 17:35:27 +0000930.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000931
Georg Brandl48310cd2009-01-03 21:18:54 +0000932 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +0000933 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000934
935
Georg Brandl3dd33882009-06-01 17:35:27 +0000936.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000937
938 Get a list of frame records for a frame and all outer frames. These frames
939 represent the calls that lead to the creation of *frame*. The first entry in the
940 returned list represents *frame*; the last entry represents the outermost call
941 on *frame*'s stack.
942
943
Georg Brandl3dd33882009-06-01 17:35:27 +0000944.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000945
946 Get a list of frame records for a traceback's frame and all inner frames. These
947 frames represent calls made as a consequence of *frame*. The first entry in the
948 list represents *traceback*; the last entry represents where the exception was
949 raised.
950
951
952.. function:: currentframe()
953
954 Return the frame object for the caller's stack frame.
955
Georg Brandl495f7b52009-10-27 15:28:25 +0000956 .. impl-detail::
957
958 This function relies on Python stack frame support in the interpreter,
959 which isn't guaranteed to exist in all implementations of Python. If
960 running in an implementation without Python stack frame support this
961 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000962
Georg Brandl116aa622007-08-15 14:28:22 +0000963
Georg Brandl3dd33882009-06-01 17:35:27 +0000964.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000965
966 Return a list of frame records for the caller's stack. The first entry in the
967 returned list represents the caller; the last entry represents the outermost
968 call on the stack.
969
970
Georg Brandl3dd33882009-06-01 17:35:27 +0000971.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000972
973 Return a list of frame records for the stack between the current frame and the
974 frame in which an exception currently being handled was raised in. The first
975 entry in the list represents the caller; the last entry represents where the
976 exception was raised.
977
Michael Foord95fc51d2010-11-20 15:07:30 +0000978
979Fetching attributes statically
980------------------------------
981
982Both :func:`getattr` and :func:`hasattr` can trigger code execution when
983fetching or checking for the existence of attributes. Descriptors, like
984properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
985may be called.
986
987For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +0200988can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +0000989but avoids executing code when it fetches attributes.
990
991.. function:: getattr_static(obj, attr, default=None)
992
993 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +0200994 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +0000995
996 Note: this function may not be able to retrieve all attributes
997 that getattr can fetch (like dynamically created attributes)
998 and may find attributes that getattr can't (like descriptors
999 that raise AttributeError). It can also return descriptors objects
1000 instead of instance members.
1001
Serhiy Storchakabfdcd432013-10-13 23:09:14 +03001002 If the instance :attr:`~object.__dict__` is shadowed by another member (for
1003 example a property) then this function will be unable to find instance
1004 members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001005
Michael Foorddcebe0f2011-03-15 19:20:44 -04001006 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +00001007
Éric Araujo941afed2011-09-01 02:47:34 +02001008:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +00001009getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +00001010is returned instead of the underlying attribute.
1011
1012You can handle these with code like the following. Note that
1013for arbitrary getset descriptors invoking these may trigger
1014code execution::
1015
1016 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +00001017 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +00001018 __slots__ = ['foo']
1019
1020 slot_descriptor = type(_foo.foo)
1021 getset_descriptor = type(type(open(__file__)).name)
1022 wrapper_descriptor = type(str.__dict__['__add__'])
1023 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
1024
1025 result = getattr_static(some_object, 'foo')
1026 if type(result) in descriptor_types:
1027 try:
1028 result = result.__get__()
1029 except AttributeError:
1030 # descriptors can raise AttributeError to
1031 # indicate there is no underlying value
1032 # in which case the descriptor itself will
1033 # have to do
1034 pass
Nick Coghlane0f04652010-11-21 03:44:04 +00001035
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001036
Nick Coghlane0f04652010-11-21 03:44:04 +00001037Current State of a Generator
1038----------------------------
1039
1040When implementing coroutine schedulers and for other advanced uses of
1041generators, it is useful to determine whether a generator is currently
1042executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001043terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +00001044generator to be determined easily.
1045
1046.. function:: getgeneratorstate(generator)
1047
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001048 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +00001049
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001050 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +00001051 * GEN_CREATED: Waiting to start execution.
1052 * GEN_RUNNING: Currently being executed by the interpreter.
1053 * GEN_SUSPENDED: Currently suspended at a yield expression.
1054 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +00001055
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001056 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001057
1058The current internal state of the generator can also be queried. This is
1059mostly useful for testing purposes, to ensure that internal state is being
1060updated as expected:
1061
1062.. function:: getgeneratorlocals(generator)
1063
1064 Get the mapping of live local variables in *generator* to their current
1065 values. A dictionary is returned that maps from variable names to values.
1066 This is the equivalent of calling :func:`locals` in the body of the
1067 generator, and all the same caveats apply.
1068
1069 If *generator* is a :term:`generator` with no currently associated frame,
1070 then an empty dictionary is returned. :exc:`TypeError` is raised if
1071 *generator* is not a Python generator object.
1072
1073 .. impl-detail::
1074
1075 This function relies on the generator exposing a Python stack frame
1076 for introspection, which isn't guaranteed to be the case in all
1077 implementations of Python. In such cases, this function will always
1078 return an empty dictionary.
1079
1080 .. versionadded:: 3.3
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001081
1082
Nick Coghlan367df122013-10-27 01:57:34 +10001083.. _inspect-module-cli:
1084
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001085Command Line Interface
1086----------------------
1087
1088The :mod:`inspect` module also provides a basic introspection capability
1089from the command line.
1090
1091.. program:: inspect
1092
1093By default, accepts the name of a module and prints the source of that
1094module. A class or function within the module can be printed instead by
1095appended a colon and the qualified name of the target object.
1096
1097.. cmdoption:: --details
1098
1099 Print information about the specified object rather than the source code