blob: 3ac66d8204e97158e7eaa2921a5a735255d9d722 [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():
681 ... if param.name not in ba.arguments:
682 ... ba.arguments[param.name] = param.default
683
684 >>> ba.args, ba.kwargs
685 ((5, 10), {})
686
687
688 .. attribute:: BoundArguments.args
689
Georg Brandle4717722012-08-14 09:45:28 +0200690 A tuple of positional arguments values. Dynamically computed from the
691 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300692
693 .. attribute:: BoundArguments.kwargs
694
Georg Brandle4717722012-08-14 09:45:28 +0200695 A dict of keyword arguments values. Dynamically computed from the
696 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300697
Georg Brandle4717722012-08-14 09:45:28 +0200698 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
699 functions::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300700
701 def test(a, *, b):
702 ...
703
704 sig = signature(test)
705 ba = sig.bind(10, b=20)
706 test(*ba.args, **ba.kwargs)
707
708
Georg Brandle4717722012-08-14 09:45:28 +0200709.. seealso::
710
711 :pep:`362` - Function Signature Object.
712 The detailed specification, implementation details and examples.
713
714
Georg Brandl116aa622007-08-15 14:28:22 +0000715.. _inspect-classes-functions:
716
717Classes and functions
718---------------------
719
Georg Brandl3dd33882009-06-01 17:35:27 +0000720.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000721
722 Arrange the given list of classes into a hierarchy of nested lists. Where a
723 nested list appears, it contains classes derived from the class whose entry
724 immediately precedes the list. Each entry is a 2-tuple containing a class and a
725 tuple of its base classes. If the *unique* argument is true, exactly one entry
726 appears in the returned structure for each class in the given list. Otherwise,
727 classes using multiple inheritance and their descendants will appear multiple
728 times.
729
730
731.. function:: getargspec(func)
732
Georg Brandl82402752010-01-09 09:48:46 +0000733 Get the names and default values of a Python function's arguments. A
Georg Brandlb30f3302011-01-06 09:23:56 +0000734 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
735 returned. *args* is a list of the argument names. *varargs* and *keywords*
736 are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700737 tuple of default argument values or ``None`` if there are no default
738 arguments; if this tuple has *n* elements, they correspond to the last
739 *n* elements listed in *args*.
Georg Brandl138bcb52007-09-12 19:04:21 +0000740
741 .. deprecated:: 3.0
742 Use :func:`getfullargspec` instead, which provides information about
Benjamin Peterson3e8e9cc2008-11-12 21:26:46 +0000743 keyword-only arguments and annotations.
Georg Brandl138bcb52007-09-12 19:04:21 +0000744
745
746.. function:: getfullargspec(func)
747
Georg Brandl82402752010-01-09 09:48:46 +0000748 Get the names and default values of a Python function's arguments. A
749 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000750
Georg Brandl3dd33882009-06-01 17:35:27 +0000751 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
752 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000753
754 *args* is a list of the argument names. *varargs* and *varkw* are the names
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700755 of the ``*`` and ``**`` arguments or ``None``. *defaults* is an *n*-tuple
756 of the default values of the last *n* arguments, or ``None`` if there are no
757 default arguments. *kwonlyargs* is a list of
Georg Brandl138bcb52007-09-12 19:04:21 +0000758 keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
759 from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
760 names to annotations.
761
762 The first four items in the tuple correspond to :func:`getargspec`.
Georg Brandl116aa622007-08-15 14:28:22 +0000763
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300764 .. note::
765 Consider using the new :ref:`Signature Object <inspect-signature-object>`
766 interface, which provides a better way of introspecting functions.
767
Nick Coghlan16355782014-03-08 16:36:37 +1000768 .. versionchanged:: 3.4
769 This function is now based on :func:`signature`, but still ignores
770 ``__wrapped__`` attributes and includes the already bound first
771 parameter in the signature output for bound methods.
772
Georg Brandl116aa622007-08-15 14:28:22 +0000773
774.. function:: getargvalues(frame)
775
Georg Brandl3dd33882009-06-01 17:35:27 +0000776 Get information about arguments passed into a particular frame. A
777 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000778 returned. *args* is a list of the argument names. *varargs* and *keywords*
779 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000780 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000781
782
Andrew Svetlov735d3172012-10-27 00:28:20 +0300783.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Georg Brandl116aa622007-08-15 14:28:22 +0000784
Michael Foord3af125a2012-04-21 18:22:28 +0100785 Format a pretty argument spec from the values returned by
786 :func:`getargspec` or :func:`getfullargspec`.
787
788 The first seven arguments are (``args``, ``varargs``, ``varkw``,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100789 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
Andrew Svetlov735d3172012-10-27 00:28:20 +0300790
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100791 The other six arguments are functions that are called to turn argument names,
792 ``*`` argument name, ``**`` argument name, default values, return annotation
793 and individual annotations into strings, respectively.
794
795 For example:
796
797 >>> from inspect import formatargspec, getfullargspec
798 >>> def f(a: int, b: float):
799 ... pass
800 ...
801 >>> formatargspec(*getfullargspec(f))
802 '(a: int, b: float)'
Georg Brandl116aa622007-08-15 14:28:22 +0000803
804
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000805.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000806
807 Format a pretty argument spec from the four values returned by
808 :func:`getargvalues`. The format\* arguments are the corresponding optional
809 formatting functions that are called to turn names and values into strings.
810
811
812.. function:: getmro(cls)
813
814 Return a tuple of class cls's base classes, including cls, in method resolution
815 order. No class appears more than once in this tuple. Note that the method
816 resolution order depends on cls's type. Unless a very peculiar user-defined
817 metatype is in use, cls will be the first element of the tuple.
818
819
Benjamin Peterson3a990c62014-01-02 12:22:30 -0600820.. function:: getcallargs(func, *args, **kwds)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000821
822 Bind the *args* and *kwds* to the argument names of the Python function or
823 method *func*, as if it was called with them. For bound methods, bind also the
824 first argument (typically named ``self``) to the associated instance. A dict
825 is returned, mapping the argument names (including the names of the ``*`` and
826 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
827 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
828 an exception because of incompatible signature, an exception of the same type
829 and the same or similar message is raised. For example::
830
831 >>> from inspect import getcallargs
832 >>> def f(a, b=1, *pos, **named):
833 ... pass
Andrew Svetlove939f382012-08-09 13:25:32 +0300834 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
835 True
836 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
837 True
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000838 >>> getcallargs(f)
839 Traceback (most recent call last):
840 ...
Andrew Svetlove939f382012-08-09 13:25:32 +0300841 TypeError: f() missing 1 required positional argument: 'a'
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000842
843 .. versionadded:: 3.2
844
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300845 .. note::
846 Consider using the new :meth:`Signature.bind` instead.
847
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000848
Nick Coghlan2f92e542012-06-23 19:39:55 +1000849.. function:: getclosurevars(func)
850
851 Get the mapping of external name references in a Python function or
852 method *func* to their current values. A
853 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
854 is returned. *nonlocals* maps referenced names to lexical closure
855 variables, *globals* to the function's module globals and *builtins* to
856 the builtins visible from the function body. *unbound* is the set of names
857 referenced in the function that could not be resolved at all given the
858 current module globals and builtins.
859
860 :exc:`TypeError` is raised if *func* is not a Python function or method.
861
862 .. versionadded:: 3.3
863
864
Nick Coghlane8c45d62013-07-28 20:00:01 +1000865.. function:: unwrap(func, *, stop=None)
866
867 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
868 attributes returning the last object in the chain.
869
870 *stop* is an optional callback accepting an object in the wrapper chain
871 as its sole argument that allows the unwrapping to be terminated early if
872 the callback returns a true value. If the callback never returns a true
873 value, the last object in the chain is returned as usual. For example,
874 :func:`signature` uses this to stop unwrapping if any object in the
875 chain has a ``__signature__`` attribute defined.
876
877 :exc:`ValueError` is raised if a cycle is encountered.
878
879 .. versionadded:: 3.4
880
881
Georg Brandl116aa622007-08-15 14:28:22 +0000882.. _inspect-stack:
883
884The interpreter stack
885---------------------
886
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400887When the following functions return "frame records," each record is a
888:term:`named tuple`
889``FrameInfo(frame, filename, lineno, function, code_context, index)``.
890The tuple contains the frame object, the filename, the line number of the
891current line,
Georg Brandl116aa622007-08-15 14:28:22 +0000892the function name, a list of lines of context from the source code, and the
893index of the current line within that list.
894
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400895.. versionchanged:: 3.5
896 Return a named tuple instead of a tuple.
897
Georg Brandle720c0a2009-04-27 16:20:50 +0000898.. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000899
900 Keeping references to frame objects, as found in the first element of the frame
901 records these functions return, can cause your program to create reference
902 cycles. Once a reference cycle has been created, the lifespan of all objects
903 which can be accessed from the objects which form the cycle can become much
904 longer even if Python's optional cycle detector is enabled. If such cycles must
905 be created, it is important to ensure they are explicitly broken to avoid the
906 delayed destruction of objects and increased memory consumption which occurs.
907
908 Though the cycle detector will catch these, destruction of the frames (and local
909 variables) can be made deterministic by removing the cycle in a
910 :keyword:`finally` clause. This is also important if the cycle detector was
911 disabled when Python was compiled or using :func:`gc.disable`. For example::
912
913 def handle_stackframe_without_leak():
914 frame = inspect.currentframe()
915 try:
916 # do something with the frame
917 finally:
918 del frame
919
Antoine Pitrou58720d62013-08-05 23:26:40 +0200920 If you want to keep the frame around (for example to print a traceback
921 later), you can also break reference cycles by using the
922 :meth:`frame.clear` method.
923
Georg Brandl116aa622007-08-15 14:28:22 +0000924The optional *context* argument supported by most of these functions specifies
925the number of lines of context to return, which are centered around the current
926line.
927
928
Georg Brandl3dd33882009-06-01 17:35:27 +0000929.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000930
Georg Brandl48310cd2009-01-03 21:18:54 +0000931 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +0000932 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000933
934
Georg Brandl3dd33882009-06-01 17:35:27 +0000935.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000936
937 Get a list of frame records for a frame and all outer frames. These frames
938 represent the calls that lead to the creation of *frame*. The first entry in the
939 returned list represents *frame*; the last entry represents the outermost call
940 on *frame*'s stack.
941
942
Georg Brandl3dd33882009-06-01 17:35:27 +0000943.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000944
945 Get a list of frame records for a traceback's frame and all inner frames. These
946 frames represent calls made as a consequence of *frame*. The first entry in the
947 list represents *traceback*; the last entry represents where the exception was
948 raised.
949
950
951.. function:: currentframe()
952
953 Return the frame object for the caller's stack frame.
954
Georg Brandl495f7b52009-10-27 15:28:25 +0000955 .. impl-detail::
956
957 This function relies on Python stack frame support in the interpreter,
958 which isn't guaranteed to exist in all implementations of Python. If
959 running in an implementation without Python stack frame support this
960 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000961
Georg Brandl116aa622007-08-15 14:28:22 +0000962
Georg Brandl3dd33882009-06-01 17:35:27 +0000963.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000964
965 Return a list of frame records for the caller's stack. The first entry in the
966 returned list represents the caller; the last entry represents the outermost
967 call on the stack.
968
969
Georg Brandl3dd33882009-06-01 17:35:27 +0000970.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000971
972 Return a list of frame records for the stack between the current frame and the
973 frame in which an exception currently being handled was raised in. The first
974 entry in the list represents the caller; the last entry represents where the
975 exception was raised.
976
Michael Foord95fc51d2010-11-20 15:07:30 +0000977
978Fetching attributes statically
979------------------------------
980
981Both :func:`getattr` and :func:`hasattr` can trigger code execution when
982fetching or checking for the existence of attributes. Descriptors, like
983properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
984may be called.
985
986For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +0200987can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +0000988but avoids executing code when it fetches attributes.
989
990.. function:: getattr_static(obj, attr, default=None)
991
992 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +0200993 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +0000994
995 Note: this function may not be able to retrieve all attributes
996 that getattr can fetch (like dynamically created attributes)
997 and may find attributes that getattr can't (like descriptors
998 that raise AttributeError). It can also return descriptors objects
999 instead of instance members.
1000
Serhiy Storchakabfdcd432013-10-13 23:09:14 +03001001 If the instance :attr:`~object.__dict__` is shadowed by another member (for
1002 example a property) then this function will be unable to find instance
1003 members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001004
Michael Foorddcebe0f2011-03-15 19:20:44 -04001005 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +00001006
Éric Araujo941afed2011-09-01 02:47:34 +02001007:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +00001008getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +00001009is returned instead of the underlying attribute.
1010
1011You can handle these with code like the following. Note that
1012for arbitrary getset descriptors invoking these may trigger
1013code execution::
1014
1015 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +00001016 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +00001017 __slots__ = ['foo']
1018
1019 slot_descriptor = type(_foo.foo)
1020 getset_descriptor = type(type(open(__file__)).name)
1021 wrapper_descriptor = type(str.__dict__['__add__'])
1022 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
1023
1024 result = getattr_static(some_object, 'foo')
1025 if type(result) in descriptor_types:
1026 try:
1027 result = result.__get__()
1028 except AttributeError:
1029 # descriptors can raise AttributeError to
1030 # indicate there is no underlying value
1031 # in which case the descriptor itself will
1032 # have to do
1033 pass
Nick Coghlane0f04652010-11-21 03:44:04 +00001034
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001035
Nick Coghlane0f04652010-11-21 03:44:04 +00001036Current State of a Generator
1037----------------------------
1038
1039When implementing coroutine schedulers and for other advanced uses of
1040generators, it is useful to determine whether a generator is currently
1041executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001042terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +00001043generator to be determined easily.
1044
1045.. function:: getgeneratorstate(generator)
1046
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001047 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +00001048
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001049 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +00001050 * GEN_CREATED: Waiting to start execution.
1051 * GEN_RUNNING: Currently being executed by the interpreter.
1052 * GEN_SUSPENDED: Currently suspended at a yield expression.
1053 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +00001054
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001055 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001056
1057The current internal state of the generator can also be queried. This is
1058mostly useful for testing purposes, to ensure that internal state is being
1059updated as expected:
1060
1061.. function:: getgeneratorlocals(generator)
1062
1063 Get the mapping of live local variables in *generator* to their current
1064 values. A dictionary is returned that maps from variable names to values.
1065 This is the equivalent of calling :func:`locals` in the body of the
1066 generator, and all the same caveats apply.
1067
1068 If *generator* is a :term:`generator` with no currently associated frame,
1069 then an empty dictionary is returned. :exc:`TypeError` is raised if
1070 *generator* is not a Python generator object.
1071
1072 .. impl-detail::
1073
1074 This function relies on the generator exposing a Python stack frame
1075 for introspection, which isn't guaranteed to be the case in all
1076 implementations of Python. In such cases, this function will always
1077 return an empty dictionary.
1078
1079 .. versionadded:: 3.3
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001080
1081
Nick Coghlan367df122013-10-27 01:57:34 +10001082.. _inspect-module-cli:
1083
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001084Command Line Interface
1085----------------------
1086
1087The :mod:`inspect` module also provides a basic introspection capability
1088from the command line.
1089
1090.. program:: inspect
1091
1092By default, accepts the name of a module and prints the source of that
1093module. A class or function within the module can be printed instead by
1094appended a colon and the qualified name of the target object.
1095
1096.. cmdoption:: --details
1097
1098 Print information about the specified object rather than the source code