blob: 471200fa7870dd5328d81c17b7ecb639ebf3103a [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`.
Serhiy Storchaka5cf2b7252015-04-03 22:38:53 +0300359 If the documentation string for an object is not provided and the object is
360 a class, a method, a property or a descriptor, retrieve the documentation
361 string from the inheritance hierarchy.
Georg Brandl116aa622007-08-15 14:28:22 +0000362
363
364.. function:: getcomments(object)
365
366 Return in a single string any lines of comments immediately preceding the
367 object's source code (for a class, function, or method), or at the top of the
368 Python source file (if the object is a module).
369
370
371.. function:: getfile(object)
372
373 Return the name of the (text or binary) file in which an object was defined.
374 This will fail with a :exc:`TypeError` if the object is a built-in module,
375 class, or function.
376
377
378.. function:: getmodule(object)
379
380 Try to guess which module an object was defined in.
381
382
383.. function:: getsourcefile(object)
384
385 Return the name of the Python source file in which an object was defined. This
386 will fail with a :exc:`TypeError` if the object is a built-in module, class, or
387 function.
388
389
390.. function:: getsourcelines(object)
391
392 Return a list of source lines and starting line number for an object. The
393 argument may be a module, class, method, function, traceback, frame, or code
394 object. The source code is returned as a list of the lines corresponding to the
395 object and the line number indicates where in the original source file the first
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200396 line of code was found. An :exc:`OSError` is raised if the source code cannot
Georg Brandl116aa622007-08-15 14:28:22 +0000397 be retrieved.
398
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200399 .. versionchanged:: 3.3
400 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
401 former.
402
Georg Brandl116aa622007-08-15 14:28:22 +0000403
404.. function:: getsource(object)
405
406 Return the text of the source code for an object. The argument may be a module,
407 class, method, function, traceback, frame, or code object. The source code is
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200408 returned as a single string. An :exc:`OSError` is raised if the source code
Georg Brandl116aa622007-08-15 14:28:22 +0000409 cannot be retrieved.
410
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200411 .. versionchanged:: 3.3
412 :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the
413 former.
414
Georg Brandl116aa622007-08-15 14:28:22 +0000415
Georg Brandl0c77a822008-06-10 16:37:50 +0000416.. function:: cleandoc(doc)
417
418 Clean up indentation from docstrings that are indented to line up with blocks
419 of code. Any whitespace that can be uniformly removed from the second line
420 onwards is removed. Also, all tabs are expanded to spaces.
421
Georg Brandl0c77a822008-06-10 16:37:50 +0000422
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300423.. _inspect-signature-object:
424
Georg Brandle4717722012-08-14 09:45:28 +0200425Introspecting callables with the Signature object
426-------------------------------------------------
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300427
428.. versionadded:: 3.3
429
Georg Brandle4717722012-08-14 09:45:28 +0200430The Signature object represents the call signature of a callable object and its
431return annotation. To retrieve a Signature object, use the :func:`signature`
432function.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300433
434.. function:: signature(callable)
435
Georg Brandle4717722012-08-14 09:45:28 +0200436 Return a :class:`Signature` object for the given ``callable``::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300437
438 >>> from inspect import signature
439 >>> def foo(a, *, b:int, **kwargs):
440 ... pass
441
442 >>> sig = signature(foo)
443
444 >>> str(sig)
445 '(a, *, b:int, **kwargs)'
446
447 >>> str(sig.parameters['b'])
448 'b:int'
449
450 >>> sig.parameters['b'].annotation
451 <class 'int'>
452
Georg Brandle4717722012-08-14 09:45:28 +0200453 Accepts a wide range of python callables, from plain functions and classes to
454 :func:`functools.partial` objects.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300455
Larry Hastings5c661892014-01-24 06:17:25 -0800456 Raises :exc:`ValueError` if no signature can be provided, and
457 :exc:`TypeError` if that type of object is not supported.
458
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300459 .. note::
460
Georg Brandle4717722012-08-14 09:45:28 +0200461 Some callables may not be introspectable in certain implementations of
Yury Selivanovd71e52f2014-01-30 00:22:57 -0500462 Python. For example, in CPython, some built-in functions defined in
463 C provide no metadata about their arguments.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300464
465
Yury Selivanov78356892014-01-30 00:10:54 -0500466.. class:: Signature(parameters=None, \*, return_annotation=Signature.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300467
Georg Brandle4717722012-08-14 09:45:28 +0200468 A Signature object represents the call signature of a function and its return
469 annotation. For each parameter accepted by the function it stores a
470 :class:`Parameter` object in its :attr:`parameters` collection.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300471
Yury Selivanov78356892014-01-30 00:10:54 -0500472 The optional *parameters* argument is a sequence of :class:`Parameter`
473 objects, which is validated to check that there are no parameters with
474 duplicate names, and that the parameters are in the right order, i.e.
475 positional-only first, then positional-or-keyword, and that parameters with
476 defaults follow parameters without defaults.
477
478 The optional *return_annotation* argument, can be an arbitrary Python object,
479 is the "return" annotation of the callable.
480
Georg Brandle4717722012-08-14 09:45:28 +0200481 Signature objects are *immutable*. Use :meth:`Signature.replace` to make a
482 modified copy.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300483
Yury Selivanov67d727e2014-03-29 13:24:14 -0400484 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400485 Signature objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400486
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300487 .. attribute:: Signature.empty
488
489 A special class-level marker to specify absence of a return annotation.
490
491 .. attribute:: Signature.parameters
492
493 An ordered mapping of parameters' names to the corresponding
494 :class:`Parameter` objects.
495
496 .. attribute:: Signature.return_annotation
497
Georg Brandle4717722012-08-14 09:45:28 +0200498 The "return" annotation for the callable. If the callable has no "return"
499 annotation, this attribute is set to :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300500
501 .. method:: Signature.bind(*args, **kwargs)
502
Georg Brandle4717722012-08-14 09:45:28 +0200503 Create a mapping from positional and keyword arguments to parameters.
504 Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
505 signature, or raises a :exc:`TypeError`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300506
507 .. method:: Signature.bind_partial(*args, **kwargs)
508
Georg Brandle4717722012-08-14 09:45:28 +0200509 Works the same way as :meth:`Signature.bind`, but allows the omission of
510 some required arguments (mimics :func:`functools.partial` behavior.)
511 Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
512 passed arguments do not match the signature.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300513
Ezio Melotti8429b672012-09-14 06:35:09 +0300514 .. method:: Signature.replace(*[, parameters][, return_annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300515
Georg Brandle4717722012-08-14 09:45:28 +0200516 Create a new Signature instance based on the instance replace was invoked
517 on. It is possible to pass different ``parameters`` and/or
518 ``return_annotation`` to override the corresponding properties of the base
519 signature. To remove return_annotation from the copied Signature, pass in
520 :attr:`Signature.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300521
522 ::
523
524 >>> def test(a, b):
525 ... pass
526 >>> sig = signature(test)
527 >>> new_sig = sig.replace(return_annotation="new return anno")
528 >>> str(new_sig)
529 "(a, b) -> 'new return anno'"
530
Yury Selivanov232b9342014-03-29 13:18:30 -0400531 .. classmethod:: Signature.from_callable(obj)
Yury Selivanovda396452014-03-27 12:09:24 -0400532
533 Return a :class:`Signature` (or its subclass) object for a given callable
534 ``obj``. This method simplifies subclassing of :class:`Signature`:
535
536 ::
537
538 class MySignature(Signature):
539 pass
540 sig = MySignature.from_callable(min)
541 assert isinstance(sig, MySignature)
542
Yury Selivanov232b9342014-03-29 13:18:30 -0400543 .. versionadded:: 3.5
544
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300545
Yury Selivanov78356892014-01-30 00:10:54 -0500546.. class:: Parameter(name, kind, \*, default=Parameter.empty, annotation=Parameter.empty)
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300547
Georg Brandle4717722012-08-14 09:45:28 +0200548 Parameter objects are *immutable*. Instead of modifying a Parameter object,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300549 you can use :meth:`Parameter.replace` to create a modified copy.
550
Yury Selivanov67d727e2014-03-29 13:24:14 -0400551 .. versionchanged:: 3.5
Yury Selivanov67ae50e2014-04-08 11:46:50 -0400552 Parameter objects are picklable and hashable.
Yury Selivanov67d727e2014-03-29 13:24:14 -0400553
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300554 .. attribute:: Parameter.empty
555
Georg Brandle4717722012-08-14 09:45:28 +0200556 A special class-level marker to specify absence of default values and
557 annotations.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300558
559 .. attribute:: Parameter.name
560
Yury Selivanov2393dca2014-01-27 15:07:58 -0500561 The name of the parameter as a string. The name must be a valid
562 Python identifier.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300563
564 .. attribute:: Parameter.default
565
Georg Brandle4717722012-08-14 09:45:28 +0200566 The default value for the parameter. If the parameter has no default
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300567 value, this attribute is set to :attr:`Parameter.empty`.
568
569 .. attribute:: Parameter.annotation
570
Georg Brandle4717722012-08-14 09:45:28 +0200571 The annotation for the parameter. If the parameter has no annotation,
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300572 this attribute is set to :attr:`Parameter.empty`.
573
574 .. attribute:: Parameter.kind
575
Georg Brandle4717722012-08-14 09:45:28 +0200576 Describes how argument values are bound to the parameter. Possible values
577 (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300578
Georg Brandl44ea77b2013-03-28 13:28:44 +0100579 .. tabularcolumns:: |l|L|
580
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300581 +------------------------+----------------------------------------------+
582 | Name | Meaning |
583 +========================+==============================================+
584 | *POSITIONAL_ONLY* | Value must be supplied as a positional |
585 | | argument. |
586 | | |
587 | | Python has no explicit syntax for defining |
588 | | positional-only parameters, but many built-in|
589 | | and extension module functions (especially |
590 | | those that accept only one or two parameters)|
591 | | accept them. |
592 +------------------------+----------------------------------------------+
593 | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
594 | | positional argument (this is the standard |
595 | | binding behaviour for functions implemented |
596 | | in Python.) |
597 +------------------------+----------------------------------------------+
598 | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
599 | | bound to any other parameter. This |
600 | | corresponds to a ``*args`` parameter in a |
601 | | Python function definition. |
602 +------------------------+----------------------------------------------+
603 | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
604 | | Keyword only parameters are those which |
605 | | appear after a ``*`` or ``*args`` entry in a |
606 | | Python function definition. |
607 +------------------------+----------------------------------------------+
608 | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
609 | | to any other parameter. This corresponds to a|
610 | | ``**kwargs`` parameter in a Python function |
611 | | definition. |
612 +------------------------+----------------------------------------------+
613
Andrew Svetloveed18082012-08-13 18:23:54 +0300614 Example: print all keyword-only arguments without default values::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300615
616 >>> def foo(a, b, *, c, d=10):
617 ... pass
618
619 >>> sig = signature(foo)
620 >>> for param in sig.parameters.values():
621 ... if (param.kind == param.KEYWORD_ONLY and
622 ... param.default is param.empty):
623 ... print('Parameter:', param)
624 Parameter: c
625
Ezio Melotti8429b672012-09-14 06:35:09 +0300626 .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300627
Georg Brandle4717722012-08-14 09:45:28 +0200628 Create a new Parameter instance based on the instance replaced was invoked
629 on. To override a :class:`Parameter` attribute, pass the corresponding
630 argument. To remove a default value or/and an annotation from a
631 Parameter, pass :attr:`Parameter.empty`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300632
633 ::
634
635 >>> from inspect import Parameter
636 >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
637 >>> str(param)
638 'foo=42'
639
640 >>> str(param.replace()) # Will create a shallow copy of 'param'
641 'foo=42'
642
643 >>> str(param.replace(default=Parameter.empty, annotation='spam'))
644 "foo:'spam'"
645
Yury Selivanov2393dca2014-01-27 15:07:58 -0500646 .. versionchanged:: 3.4
647 In Python 3.3 Parameter objects were allowed to have ``name`` set
648 to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``.
649 This is no longer permitted.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300650
651.. class:: BoundArguments
652
653 Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
654 Holds the mapping of arguments to the function's parameters.
655
656 .. attribute:: BoundArguments.arguments
657
658 An ordered, mutable mapping (:class:`collections.OrderedDict`) of
Georg Brandle4717722012-08-14 09:45:28 +0200659 parameters' names to arguments' values. Contains only explicitly bound
660 arguments. Changes in :attr:`arguments` will reflect in :attr:`args` and
661 :attr:`kwargs`.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300662
Georg Brandle4717722012-08-14 09:45:28 +0200663 Should be used in conjunction with :attr:`Signature.parameters` for any
664 argument processing purposes.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300665
666 .. note::
667
668 Arguments for which :meth:`Signature.bind` or
669 :meth:`Signature.bind_partial` relied on a default value are skipped.
Georg Brandle4717722012-08-14 09:45:28 +0200670 However, if needed, it is easy to include them.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300671
672 ::
673
674 >>> def foo(a, b=10):
675 ... pass
676
677 >>> sig = signature(foo)
678 >>> ba = sig.bind(5)
679
680 >>> ba.args, ba.kwargs
681 ((5,), {})
682
683 >>> for param in sig.parameters.values():
Yury Selivanoved648a32014-12-04 22:48:47 -0500684 ... if (param.name not in ba.arguments
685 ... and param.default is not param.empty):
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300686 ... ba.arguments[param.name] = param.default
687
688 >>> ba.args, ba.kwargs
689 ((5, 10), {})
690
691
692 .. attribute:: BoundArguments.args
693
Georg Brandle4717722012-08-14 09:45:28 +0200694 A tuple of positional arguments values. Dynamically computed from the
695 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300696
697 .. attribute:: BoundArguments.kwargs
698
Georg Brandle4717722012-08-14 09:45:28 +0200699 A dict of keyword arguments values. Dynamically computed from the
700 :attr:`arguments` attribute.
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300701
Georg Brandle4717722012-08-14 09:45:28 +0200702 The :attr:`args` and :attr:`kwargs` properties can be used to invoke
703 functions::
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300704
705 def test(a, *, b):
706 ...
707
708 sig = signature(test)
709 ba = sig.bind(10, b=20)
710 test(*ba.args, **ba.kwargs)
711
712
Georg Brandle4717722012-08-14 09:45:28 +0200713.. seealso::
714
715 :pep:`362` - Function Signature Object.
716 The detailed specification, implementation details and examples.
717
718
Georg Brandl116aa622007-08-15 14:28:22 +0000719.. _inspect-classes-functions:
720
721Classes and functions
722---------------------
723
Georg Brandl3dd33882009-06-01 17:35:27 +0000724.. function:: getclasstree(classes, unique=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000725
726 Arrange the given list of classes into a hierarchy of nested lists. Where a
727 nested list appears, it contains classes derived from the class whose entry
728 immediately precedes the list. Each entry is a 2-tuple containing a class and a
729 tuple of its base classes. If the *unique* argument is true, exactly one entry
730 appears in the returned structure for each class in the given list. Otherwise,
731 classes using multiple inheritance and their descendants will appear multiple
732 times.
733
734
735.. function:: getargspec(func)
736
Georg Brandl82402752010-01-09 09:48:46 +0000737 Get the names and default values of a Python function's arguments. A
Georg Brandlb30f3302011-01-06 09:23:56 +0000738 :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
739 returned. *args* is a list of the argument names. *varargs* and *keywords*
740 are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700741 tuple of default argument values or ``None`` if there are no default
742 arguments; if this tuple has *n* elements, they correspond to the last
743 *n* elements listed in *args*.
Georg Brandl138bcb52007-09-12 19:04:21 +0000744
745 .. deprecated:: 3.0
746 Use :func:`getfullargspec` instead, which provides information about
Benjamin Peterson3e8e9cc2008-11-12 21:26:46 +0000747 keyword-only arguments and annotations.
Georg Brandl138bcb52007-09-12 19:04:21 +0000748
749
750.. function:: getfullargspec(func)
751
Georg Brandl82402752010-01-09 09:48:46 +0000752 Get the names and default values of a Python function's arguments. A
753 :term:`named tuple` is returned:
Georg Brandl138bcb52007-09-12 19:04:21 +0000754
Georg Brandl3dd33882009-06-01 17:35:27 +0000755 ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults,
756 annotations)``
Georg Brandl138bcb52007-09-12 19:04:21 +0000757
758 *args* is a list of the argument names. *varargs* and *varkw* are the names
Larry Hastingsbf84bba2012-09-21 09:40:41 -0700759 of the ``*`` and ``**`` arguments or ``None``. *defaults* is an *n*-tuple
760 of the default values of the last *n* arguments, or ``None`` if there are no
761 default arguments. *kwonlyargs* is a list of
Georg Brandl138bcb52007-09-12 19:04:21 +0000762 keyword-only argument names. *kwonlydefaults* is a dictionary mapping names
763 from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
764 names to annotations.
765
766 The first four items in the tuple correspond to :func:`getargspec`.
Georg Brandl116aa622007-08-15 14:28:22 +0000767
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300768 .. note::
769 Consider using the new :ref:`Signature Object <inspect-signature-object>`
770 interface, which provides a better way of introspecting functions.
771
Nick Coghlan16355782014-03-08 16:36:37 +1000772 .. versionchanged:: 3.4
773 This function is now based on :func:`signature`, but still ignores
774 ``__wrapped__`` attributes and includes the already bound first
775 parameter in the signature output for bound methods.
776
Georg Brandl116aa622007-08-15 14:28:22 +0000777
778.. function:: getargvalues(frame)
779
Georg Brandl3dd33882009-06-01 17:35:27 +0000780 Get information about arguments passed into a particular frame. A
781 :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
Georg Brandlb30f3302011-01-06 09:23:56 +0000782 returned. *args* is a list of the argument names. *varargs* and *keywords*
783 are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000784 locals dictionary of the given frame.
Georg Brandl116aa622007-08-15 14:28:22 +0000785
786
Andrew Svetlov735d3172012-10-27 00:28:20 +0300787.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Georg Brandl116aa622007-08-15 14:28:22 +0000788
Michael Foord3af125a2012-04-21 18:22:28 +0100789 Format a pretty argument spec from the values returned by
790 :func:`getargspec` or :func:`getfullargspec`.
791
792 The first seven arguments are (``args``, ``varargs``, ``varkw``,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100793 ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
Andrew Svetlov735d3172012-10-27 00:28:20 +0300794
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100795 The other six arguments are functions that are called to turn argument names,
796 ``*`` argument name, ``**`` argument name, default values, return annotation
797 and individual annotations into strings, respectively.
798
799 For example:
800
801 >>> from inspect import formatargspec, getfullargspec
802 >>> def f(a: int, b: float):
803 ... pass
804 ...
805 >>> formatargspec(*getfullargspec(f))
806 '(a: int, b: float)'
Georg Brandl116aa622007-08-15 14:28:22 +0000807
808
Georg Brandlc1c4bf82010-10-15 16:07:41 +0000809.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811 Format a pretty argument spec from the four values returned by
812 :func:`getargvalues`. The format\* arguments are the corresponding optional
813 formatting functions that are called to turn names and values into strings.
814
815
816.. function:: getmro(cls)
817
818 Return a tuple of class cls's base classes, including cls, in method resolution
819 order. No class appears more than once in this tuple. Note that the method
820 resolution order depends on cls's type. Unless a very peculiar user-defined
821 metatype is in use, cls will be the first element of the tuple.
822
823
Benjamin Peterson3a990c62014-01-02 12:22:30 -0600824.. function:: getcallargs(func, *args, **kwds)
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000825
826 Bind the *args* and *kwds* to the argument names of the Python function or
827 method *func*, as if it was called with them. For bound methods, bind also the
828 first argument (typically named ``self``) to the associated instance. A dict
829 is returned, mapping the argument names (including the names of the ``*`` and
830 ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
831 invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
832 an exception because of incompatible signature, an exception of the same type
833 and the same or similar message is raised. For example::
834
835 >>> from inspect import getcallargs
836 >>> def f(a, b=1, *pos, **named):
837 ... pass
Andrew Svetlove939f382012-08-09 13:25:32 +0300838 >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
839 True
840 >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
841 True
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000842 >>> getcallargs(f)
843 Traceback (most recent call last):
844 ...
Andrew Svetlove939f382012-08-09 13:25:32 +0300845 TypeError: f() missing 1 required positional argument: 'a'
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000846
847 .. versionadded:: 3.2
848
Andrew Svetlov4e48bf92012-08-13 17:10:28 +0300849 .. note::
850 Consider using the new :meth:`Signature.bind` instead.
851
Benjamin Peterson25cd7eb2010-03-30 18:42:32 +0000852
Nick Coghlan2f92e542012-06-23 19:39:55 +1000853.. function:: getclosurevars(func)
854
855 Get the mapping of external name references in a Python function or
856 method *func* to their current values. A
857 :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)``
858 is returned. *nonlocals* maps referenced names to lexical closure
859 variables, *globals* to the function's module globals and *builtins* to
860 the builtins visible from the function body. *unbound* is the set of names
861 referenced in the function that could not be resolved at all given the
862 current module globals and builtins.
863
864 :exc:`TypeError` is raised if *func* is not a Python function or method.
865
866 .. versionadded:: 3.3
867
868
Nick Coghlane8c45d62013-07-28 20:00:01 +1000869.. function:: unwrap(func, *, stop=None)
870
871 Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__`
872 attributes returning the last object in the chain.
873
874 *stop* is an optional callback accepting an object in the wrapper chain
875 as its sole argument that allows the unwrapping to be terminated early if
876 the callback returns a true value. If the callback never returns a true
877 value, the last object in the chain is returned as usual. For example,
878 :func:`signature` uses this to stop unwrapping if any object in the
879 chain has a ``__signature__`` attribute defined.
880
881 :exc:`ValueError` is raised if a cycle is encountered.
882
883 .. versionadded:: 3.4
884
885
Georg Brandl116aa622007-08-15 14:28:22 +0000886.. _inspect-stack:
887
888The interpreter stack
889---------------------
890
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400891When the following functions return "frame records," each record is a
892:term:`named tuple`
893``FrameInfo(frame, filename, lineno, function, code_context, index)``.
894The tuple contains the frame object, the filename, the line number of the
895current line,
Georg Brandl116aa622007-08-15 14:28:22 +0000896the function name, a list of lines of context from the source code, and the
897index of the current line within that list.
898
Antoine Pitroucdcafb72014-08-24 10:50:28 -0400899.. versionchanged:: 3.5
900 Return a named tuple instead of a tuple.
901
Georg Brandle720c0a2009-04-27 16:20:50 +0000902.. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000903
904 Keeping references to frame objects, as found in the first element of the frame
905 records these functions return, can cause your program to create reference
906 cycles. Once a reference cycle has been created, the lifespan of all objects
907 which can be accessed from the objects which form the cycle can become much
908 longer even if Python's optional cycle detector is enabled. If such cycles must
909 be created, it is important to ensure they are explicitly broken to avoid the
910 delayed destruction of objects and increased memory consumption which occurs.
911
912 Though the cycle detector will catch these, destruction of the frames (and local
913 variables) can be made deterministic by removing the cycle in a
914 :keyword:`finally` clause. This is also important if the cycle detector was
915 disabled when Python was compiled or using :func:`gc.disable`. For example::
916
917 def handle_stackframe_without_leak():
918 frame = inspect.currentframe()
919 try:
920 # do something with the frame
921 finally:
922 del frame
923
Antoine Pitrou58720d62013-08-05 23:26:40 +0200924 If you want to keep the frame around (for example to print a traceback
925 later), you can also break reference cycles by using the
926 :meth:`frame.clear` method.
927
Georg Brandl116aa622007-08-15 14:28:22 +0000928The optional *context* argument supported by most of these functions specifies
929the number of lines of context to return, which are centered around the current
930line.
931
932
Georg Brandl3dd33882009-06-01 17:35:27 +0000933.. function:: getframeinfo(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000934
Georg Brandl48310cd2009-01-03 21:18:54 +0000935 Get information about a frame or traceback object. A :term:`named tuple`
Christian Heimes25bb7832008-01-11 16:17:00 +0000936 ``Traceback(filename, lineno, function, code_context, index)`` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000937
938
Georg Brandl3dd33882009-06-01 17:35:27 +0000939.. function:: getouterframes(frame, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000940
941 Get a list of frame records for a frame and all outer frames. These frames
942 represent the calls that lead to the creation of *frame*. The first entry in the
943 returned list represents *frame*; the last entry represents the outermost call
944 on *frame*'s stack.
945
946
Georg Brandl3dd33882009-06-01 17:35:27 +0000947.. function:: getinnerframes(traceback, context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000948
949 Get a list of frame records for a traceback's frame and all inner frames. These
950 frames represent calls made as a consequence of *frame*. The first entry in the
951 list represents *traceback*; the last entry represents where the exception was
952 raised.
953
954
955.. function:: currentframe()
956
957 Return the frame object for the caller's stack frame.
958
Georg Brandl495f7b52009-10-27 15:28:25 +0000959 .. impl-detail::
960
961 This function relies on Python stack frame support in the interpreter,
962 which isn't guaranteed to exist in all implementations of Python. If
963 running in an implementation without Python stack frame support this
964 function returns ``None``.
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000965
Georg Brandl116aa622007-08-15 14:28:22 +0000966
Georg Brandl3dd33882009-06-01 17:35:27 +0000967.. function:: stack(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000968
969 Return a list of frame records for the caller's stack. The first entry in the
970 returned list represents the caller; the last entry represents the outermost
971 call on the stack.
972
973
Georg Brandl3dd33882009-06-01 17:35:27 +0000974.. function:: trace(context=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000975
976 Return a list of frame records for the stack between the current frame and the
977 frame in which an exception currently being handled was raised in. The first
978 entry in the list represents the caller; the last entry represents where the
979 exception was raised.
980
Michael Foord95fc51d2010-11-20 15:07:30 +0000981
982Fetching attributes statically
983------------------------------
984
985Both :func:`getattr` and :func:`hasattr` can trigger code execution when
986fetching or checking for the existence of attributes. Descriptors, like
987properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
988may be called.
989
990For cases where you want passive introspection, like documentation tools, this
Éric Araujo941afed2011-09-01 02:47:34 +0200991can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr`
Michael Foord95fc51d2010-11-20 15:07:30 +0000992but avoids executing code when it fetches attributes.
993
994.. function:: getattr_static(obj, attr, default=None)
995
996 Retrieve attributes without triggering dynamic lookup via the
Éric Araujo941afed2011-09-01 02:47:34 +0200997 descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`.
Michael Foord95fc51d2010-11-20 15:07:30 +0000998
999 Note: this function may not be able to retrieve all attributes
1000 that getattr can fetch (like dynamically created attributes)
1001 and may find attributes that getattr can't (like descriptors
1002 that raise AttributeError). It can also return descriptors objects
1003 instead of instance members.
1004
Serhiy Storchakabfdcd432013-10-13 23:09:14 +03001005 If the instance :attr:`~object.__dict__` is shadowed by another member (for
1006 example a property) then this function will be unable to find instance
1007 members.
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001008
Michael Foorddcebe0f2011-03-15 19:20:44 -04001009 .. versionadded:: 3.2
Michael Foord95fc51d2010-11-20 15:07:30 +00001010
Éric Araujo941afed2011-09-01 02:47:34 +02001011:func:`getattr_static` does not resolve descriptors, for example slot descriptors or
Michael Foorde5162652010-11-20 16:40:44 +00001012getset descriptors on objects implemented in C. The descriptor object
Michael Foord95fc51d2010-11-20 15:07:30 +00001013is returned instead of the underlying attribute.
1014
1015You can handle these with code like the following. Note that
1016for arbitrary getset descriptors invoking these may trigger
1017code execution::
1018
1019 # example code for resolving the builtin descriptor types
Éric Araujo28053fb2010-11-22 03:09:19 +00001020 class _foo:
Michael Foord95fc51d2010-11-20 15:07:30 +00001021 __slots__ = ['foo']
1022
1023 slot_descriptor = type(_foo.foo)
1024 getset_descriptor = type(type(open(__file__)).name)
1025 wrapper_descriptor = type(str.__dict__['__add__'])
1026 descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
1027
1028 result = getattr_static(some_object, 'foo')
1029 if type(result) in descriptor_types:
1030 try:
1031 result = result.__get__()
1032 except AttributeError:
1033 # descriptors can raise AttributeError to
1034 # indicate there is no underlying value
1035 # in which case the descriptor itself will
1036 # have to do
1037 pass
Nick Coghlane0f04652010-11-21 03:44:04 +00001038
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001039
Nick Coghlane0f04652010-11-21 03:44:04 +00001040Current State of a Generator
1041----------------------------
1042
1043When implementing coroutine schedulers and for other advanced uses of
1044generators, it is useful to determine whether a generator is currently
1045executing, is waiting to start or resume or execution, or has already
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001046terminated. :func:`getgeneratorstate` allows the current state of a
Nick Coghlane0f04652010-11-21 03:44:04 +00001047generator to be determined easily.
1048
1049.. function:: getgeneratorstate(generator)
1050
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001051 Get current state of a generator-iterator.
Nick Coghlane0f04652010-11-21 03:44:04 +00001052
Raymond Hettinger48f3bd32010-12-16 00:30:53 +00001053 Possible states are:
Raymond Hettingera275c982011-01-20 04:03:19 +00001054 * GEN_CREATED: Waiting to start execution.
1055 * GEN_RUNNING: Currently being executed by the interpreter.
1056 * GEN_SUSPENDED: Currently suspended at a yield expression.
1057 * GEN_CLOSED: Execution has completed.
Nick Coghlane0f04652010-11-21 03:44:04 +00001058
Nick Coghlan2dad5ca2010-11-21 03:55:53 +00001059 .. versionadded:: 3.2
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001060
1061The current internal state of the generator can also be queried. This is
1062mostly useful for testing purposes, to ensure that internal state is being
1063updated as expected:
1064
1065.. function:: getgeneratorlocals(generator)
1066
1067 Get the mapping of live local variables in *generator* to their current
1068 values. A dictionary is returned that maps from variable names to values.
1069 This is the equivalent of calling :func:`locals` in the body of the
1070 generator, and all the same caveats apply.
1071
1072 If *generator* is a :term:`generator` with no currently associated frame,
1073 then an empty dictionary is returned. :exc:`TypeError` is raised if
1074 *generator* is not a Python generator object.
1075
1076 .. impl-detail::
1077
1078 This function relies on the generator exposing a Python stack frame
1079 for introspection, which isn't guaranteed to be the case in all
1080 implementations of Python. In such cases, this function will always
1081 return an empty dictionary.
1082
1083 .. versionadded:: 3.3
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001084
1085
Nick Coghlan367df122013-10-27 01:57:34 +10001086.. _inspect-module-cli:
1087
Nick Coghlanf94a16b2013-09-22 22:46:49 +10001088Command Line Interface
1089----------------------
1090
1091The :mod:`inspect` module also provides a basic introspection capability
1092from the command line.
1093
1094.. program:: inspect
1095
1096By default, accepts the name of a module and prints the source of that
1097module. A class or function within the module can be printed instead by
1098appended a colon and the qualified name of the target object.
1099
1100.. cmdoption:: --details
1101
1102 Print information about the specified object rather than the source code