Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | :mod:`inspect` --- Inspect live objects |
| 2 | ======================================= |
| 3 | |
| 4 | .. module:: inspect |
| 5 | :synopsis: Extract information and source code from live objects. |
Terry Jan Reedy | fa089b9 | 2016-06-11 15:02:54 -0400 | [diff] [blame] | 6 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 7 | .. moduleauthor:: Ka-Ping Yee <ping@lfw.org> |
| 8 | .. sectionauthor:: Ka-Ping Yee <ping@lfw.org> |
| 9 | |
Raymond Hettinger | 469271d | 2011-01-27 20:38:46 +0000 | [diff] [blame] | 10 | **Source code:** :source:`Lib/inspect.py` |
| 11 | |
| 12 | -------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 13 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 14 | The :mod:`inspect` module provides several useful functions to help get |
| 15 | information about live objects such as modules, classes, methods, functions, |
| 16 | tracebacks, frame objects, and code objects. For example, it can help you |
| 17 | examine the contents of a class, retrieve the source code of a method, extract |
| 18 | and format the argument list for a function, or get all the information you need |
| 19 | to display a detailed traceback. |
| 20 | |
| 21 | There are four main kinds of services provided by this module: type checking, |
| 22 | getting source code, inspecting classes and functions, and examining the |
| 23 | interpreter stack. |
| 24 | |
| 25 | |
| 26 | .. _inspect-types: |
| 27 | |
| 28 | Types and members |
| 29 | ----------------- |
| 30 | |
| 31 | The :func:`getmembers` function retrieves the members of an object such as a |
Yury Selivanov | 59a3b67 | 2015-06-30 22:06:42 -0400 | [diff] [blame] | 32 | class or module. The functions whose names begin with "is" are mainly |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 33 | provided as convenient choices for the second argument to :func:`getmembers`. |
| 34 | They also help you determine when you can expect to find the following special |
| 35 | attributes: |
| 36 | |
Eric Snow | 4f29e75 | 2016-09-08 15:11:11 -0700 | [diff] [blame] | 37 | +-----------+-----------------+---------------------------+ |
| 38 | | Type | Attribute | Description | |
| 39 | +===========+=================+===========================+ |
| 40 | | module | __doc__ | documentation string | |
| 41 | +-----------+-----------------+---------------------------+ |
| 42 | | | __file__ | filename (missing for | |
| 43 | | | | built-in modules) | |
| 44 | +-----------+-----------------+---------------------------+ |
| 45 | | class | __doc__ | documentation string | |
| 46 | +-----------+-----------------+---------------------------+ |
| 47 | | | __name__ | name with which this | |
| 48 | | | | class was defined | |
| 49 | +-----------+-----------------+---------------------------+ |
| 50 | | | __qualname__ | qualified name | |
| 51 | +-----------+-----------------+---------------------------+ |
| 52 | | | __module__ | name of module in which | |
| 53 | | | | this class was defined | |
| 54 | +-----------+-----------------+---------------------------+ |
| 55 | | method | __doc__ | documentation string | |
| 56 | +-----------+-----------------+---------------------------+ |
| 57 | | | __name__ | name with which this | |
| 58 | | | | method was defined | |
| 59 | +-----------+-----------------+---------------------------+ |
| 60 | | | __qualname__ | qualified name | |
| 61 | +-----------+-----------------+---------------------------+ |
| 62 | | | __func__ | function object | |
| 63 | | | | containing implementation | |
| 64 | | | | of method | |
| 65 | +-----------+-----------------+---------------------------+ |
| 66 | | | __self__ | instance to which this | |
| 67 | | | | method is bound, or | |
| 68 | | | | ``None`` | |
| 69 | +-----------+-----------------+---------------------------+ |
| 70 | | function | __doc__ | documentation string | |
| 71 | +-----------+-----------------+---------------------------+ |
| 72 | | | __name__ | name with which this | |
| 73 | | | | function was defined | |
| 74 | +-----------+-----------------+---------------------------+ |
| 75 | | | __qualname__ | qualified name | |
| 76 | +-----------+-----------------+---------------------------+ |
| 77 | | | __code__ | code object containing | |
| 78 | | | | compiled function | |
| 79 | | | | :term:`bytecode` | |
| 80 | +-----------+-----------------+---------------------------+ |
| 81 | | | __defaults__ | tuple of any default | |
| 82 | | | | values for positional or | |
| 83 | | | | keyword parameters | |
| 84 | +-----------+-----------------+---------------------------+ |
| 85 | | | __kwdefaults__ | mapping of any default | |
| 86 | | | | values for keyword-only | |
| 87 | | | | parameters | |
| 88 | +-----------+-----------------+---------------------------+ |
| 89 | | | __globals__ | global namespace in which | |
| 90 | | | | this function was defined | |
| 91 | +-----------+-----------------+---------------------------+ |
| 92 | | | __annotations__ | mapping of parameters | |
| 93 | | | | names to annotations; | |
| 94 | | | | ``"return"`` key is | |
| 95 | | | | reserved for return | |
| 96 | | | | annotations. | |
| 97 | +-----------+-----------------+---------------------------+ |
| 98 | | traceback | tb_frame | frame object at this | |
| 99 | | | | level | |
| 100 | +-----------+-----------------+---------------------------+ |
| 101 | | | tb_lasti | index of last attempted | |
| 102 | | | | instruction in bytecode | |
| 103 | +-----------+-----------------+---------------------------+ |
| 104 | | | tb_lineno | current line number in | |
| 105 | | | | Python source code | |
| 106 | +-----------+-----------------+---------------------------+ |
| 107 | | | tb_next | next inner traceback | |
| 108 | | | | object (called by this | |
| 109 | | | | level) | |
| 110 | +-----------+-----------------+---------------------------+ |
| 111 | | frame | f_back | next outer frame object | |
| 112 | | | | (this frame's caller) | |
| 113 | +-----------+-----------------+---------------------------+ |
| 114 | | | f_builtins | builtins namespace seen | |
| 115 | | | | by this frame | |
| 116 | +-----------+-----------------+---------------------------+ |
| 117 | | | f_code | code object being | |
| 118 | | | | executed in this frame | |
| 119 | +-----------+-----------------+---------------------------+ |
| 120 | | | f_globals | global namespace seen by | |
| 121 | | | | this frame | |
| 122 | +-----------+-----------------+---------------------------+ |
| 123 | | | f_lasti | index of last attempted | |
| 124 | | | | instruction in bytecode | |
| 125 | +-----------+-----------------+---------------------------+ |
| 126 | | | f_lineno | current line number in | |
| 127 | | | | Python source code | |
| 128 | +-----------+-----------------+---------------------------+ |
| 129 | | | f_locals | local namespace seen by | |
| 130 | | | | this frame | |
| 131 | +-----------+-----------------+---------------------------+ |
| 132 | | | f_restricted | 0 or 1 if frame is in | |
| 133 | | | | restricted execution mode | |
| 134 | +-----------+-----------------+---------------------------+ |
| 135 | | | f_trace | tracing function for this | |
| 136 | | | | frame, or ``None`` | |
| 137 | +-----------+-----------------+---------------------------+ |
| 138 | | code | co_argcount | number of arguments (not | |
| 139 | | | | including \* or \*\* | |
| 140 | | | | args) | |
| 141 | +-----------+-----------------+---------------------------+ |
| 142 | | | co_code | string of raw compiled | |
| 143 | | | | bytecode | |
| 144 | +-----------+-----------------+---------------------------+ |
| 145 | | | co_consts | tuple of constants used | |
| 146 | | | | in the bytecode | |
| 147 | +-----------+-----------------+---------------------------+ |
| 148 | | | co_filename | name of file in which | |
| 149 | | | | this code object was | |
| 150 | | | | created | |
| 151 | +-----------+-----------------+---------------------------+ |
| 152 | | | co_firstlineno | number of first line in | |
| 153 | | | | Python source code | |
| 154 | +-----------+-----------------+---------------------------+ |
Yury Selivanov | ea75a51 | 2016-10-20 13:06:30 -0400 | [diff] [blame] | 155 | | | co_flags | bitmap of ``CO_*`` flags, | |
| 156 | | | | read more :ref:`here | |
| 157 | | | | <inspect-module-co-flags>`| |
Eric Snow | 4f29e75 | 2016-09-08 15:11:11 -0700 | [diff] [blame] | 158 | +-----------+-----------------+---------------------------+ |
| 159 | | | co_lnotab | encoded mapping of line | |
| 160 | | | | numbers to bytecode | |
| 161 | | | | indices | |
| 162 | +-----------+-----------------+---------------------------+ |
| 163 | | | co_name | name with which this code | |
| 164 | | | | object was defined | |
| 165 | +-----------+-----------------+---------------------------+ |
| 166 | | | co_names | tuple of names of local | |
| 167 | | | | variables | |
| 168 | +-----------+-----------------+---------------------------+ |
| 169 | | | co_nlocals | number of local variables | |
| 170 | +-----------+-----------------+---------------------------+ |
| 171 | | | co_stacksize | virtual machine stack | |
| 172 | | | | space required | |
| 173 | +-----------+-----------------+---------------------------+ |
| 174 | | | co_varnames | tuple of names of | |
| 175 | | | | arguments and local | |
| 176 | | | | variables | |
| 177 | +-----------+-----------------+---------------------------+ |
| 178 | | generator | __name__ | name | |
| 179 | +-----------+-----------------+---------------------------+ |
| 180 | | | __qualname__ | qualified name | |
| 181 | +-----------+-----------------+---------------------------+ |
| 182 | | | gi_frame | frame | |
| 183 | +-----------+-----------------+---------------------------+ |
| 184 | | | gi_running | is the generator running? | |
| 185 | +-----------+-----------------+---------------------------+ |
| 186 | | | gi_code | code | |
| 187 | +-----------+-----------------+---------------------------+ |
| 188 | | | gi_yieldfrom | object being iterated by | |
| 189 | | | | ``yield from``, or | |
| 190 | | | | ``None`` | |
| 191 | +-----------+-----------------+---------------------------+ |
| 192 | | coroutine | __name__ | name | |
| 193 | +-----------+-----------------+---------------------------+ |
| 194 | | | __qualname__ | qualified name | |
| 195 | +-----------+-----------------+---------------------------+ |
| 196 | | | cr_await | object being awaited on, | |
| 197 | | | | or ``None`` | |
| 198 | +-----------+-----------------+---------------------------+ |
| 199 | | | cr_frame | frame | |
| 200 | +-----------+-----------------+---------------------------+ |
| 201 | | | cr_running | is the coroutine running? | |
| 202 | +-----------+-----------------+---------------------------+ |
| 203 | | | cr_code | code | |
| 204 | +-----------+-----------------+---------------------------+ |
| 205 | | builtin | __doc__ | documentation string | |
| 206 | +-----------+-----------------+---------------------------+ |
| 207 | | | __name__ | original name of this | |
| 208 | | | | function or method | |
| 209 | +-----------+-----------------+---------------------------+ |
| 210 | | | __qualname__ | qualified name | |
| 211 | +-----------+-----------------+---------------------------+ |
| 212 | | | __self__ | instance to which a | |
| 213 | | | | method is bound, or | |
| 214 | | | | ``None`` | |
| 215 | +-----------+-----------------+---------------------------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 216 | |
Victor Stinner | 40ee301 | 2014-06-16 15:59:28 +0200 | [diff] [blame] | 217 | .. versionchanged:: 3.5 |
| 218 | |
Yury Selivanov | 5fbad3c | 2015-08-17 13:04:41 -0400 | [diff] [blame] | 219 | Add ``__qualname__`` and ``gi_yieldfrom`` attributes to generators. |
| 220 | |
| 221 | The ``__name__`` attribute of generators is now set from the function |
| 222 | name, instead of the code name, and it can now be modified. |
Victor Stinner | 40ee301 | 2014-06-16 15:59:28 +0200 | [diff] [blame] | 223 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 224 | |
| 225 | .. function:: getmembers(object[, predicate]) |
| 226 | |
| 227 | Return all the members of an object in a list of (name, value) pairs sorted by |
| 228 | name. If the optional *predicate* argument is supplied, only members for which |
| 229 | the predicate returns a true value are included. |
| 230 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 231 | .. note:: |
| 232 | |
Ethan Furman | 63c141c | 2013-10-18 00:27:39 -0700 | [diff] [blame] | 233 | :func:`getmembers` will only return class attributes defined in the |
| 234 | metaclass when the argument is a class and those attributes have been |
| 235 | listed in the metaclass' custom :meth:`__dir__`. |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 236 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 237 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 238 | .. function:: getmodulename(path) |
| 239 | |
| 240 | Return the name of the module named by the file *path*, without including the |
Nick Coghlan | 76e0770 | 2012-07-18 23:14:57 +1000 | [diff] [blame] | 241 | names of enclosing packages. The file extension is checked against all of |
| 242 | the entries in :func:`importlib.machinery.all_suffixes`. If it matches, |
| 243 | the final path component is returned with the extension removed. |
| 244 | Otherwise, ``None`` is returned. |
| 245 | |
| 246 | Note that this function *only* returns a meaningful name for actual |
| 247 | Python modules - paths that potentially refer to Python packages will |
| 248 | still return ``None``. |
| 249 | |
| 250 | .. versionchanged:: 3.3 |
Yury Selivanov | 6dfbc5d | 2015-07-23 17:49:00 +0300 | [diff] [blame] | 251 | The function is based directly on :mod:`importlib`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 252 | |
| 253 | |
| 254 | .. function:: ismodule(object) |
| 255 | |
| 256 | Return true if the object is a module. |
| 257 | |
| 258 | |
| 259 | .. function:: isclass(object) |
| 260 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 261 | Return true if the object is a class, whether built-in or created in Python |
| 262 | code. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 263 | |
| 264 | |
| 265 | .. function:: ismethod(object) |
| 266 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 267 | Return true if the object is a bound method written in Python. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 268 | |
| 269 | |
| 270 | .. function:: isfunction(object) |
| 271 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 272 | Return true if the object is a Python function, which includes functions |
| 273 | created by a :term:`lambda` expression. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 274 | |
| 275 | |
Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 276 | .. function:: isgeneratorfunction(object) |
| 277 | |
| 278 | Return true if the object is a Python generator function. |
| 279 | |
| 280 | |
| 281 | .. function:: isgenerator(object) |
| 282 | |
| 283 | Return true if the object is a generator. |
| 284 | |
| 285 | |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 286 | .. function:: iscoroutinefunction(object) |
| 287 | |
Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 288 | Return true if the object is a :term:`coroutine function` |
| 289 | (a function defined with an :keyword:`async def` syntax). |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 290 | |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 291 | .. versionadded:: 3.5 |
| 292 | |
| 293 | |
| 294 | .. function:: iscoroutine(object) |
| 295 | |
Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 296 | Return true if the object is a :term:`coroutine` created by an |
| 297 | :keyword:`async def` function. |
Yury Selivanov | f3e40fa | 2015-05-21 11:50:30 -0400 | [diff] [blame] | 298 | |
| 299 | .. versionadded:: 3.5 |
| 300 | |
| 301 | |
Yury Selivanov | fdbeb2b | 2015-07-03 13:11:35 -0400 | [diff] [blame] | 302 | .. function:: isawaitable(object) |
| 303 | |
| 304 | Return true if the object can be used in :keyword:`await` expression. |
| 305 | |
| 306 | Can also be used to distinguish generator-based coroutines from regular |
| 307 | generators:: |
| 308 | |
| 309 | def gen(): |
| 310 | yield |
| 311 | @types.coroutine |
| 312 | def gen_coro(): |
| 313 | yield |
| 314 | |
| 315 | assert not isawaitable(gen()) |
| 316 | assert isawaitable(gen_coro()) |
| 317 | |
| 318 | .. versionadded:: 3.5 |
| 319 | |
| 320 | |
Yury Selivanov | 0366004 | 2016-12-15 17:36:05 -0500 | [diff] [blame] | 321 | .. function:: isasyncgenfunction(object) |
| 322 | |
| 323 | Return true if the object is an :term:`asynchronous generator` function, |
| 324 | for example:: |
| 325 | |
| 326 | >>> async def agen(): |
| 327 | ... yield 1 |
| 328 | ... |
| 329 | >>> inspect.isasyncgenfunction(agen) |
| 330 | True |
| 331 | |
| 332 | .. versionadded:: 3.6 |
| 333 | |
| 334 | |
| 335 | .. function:: isasyncgen(object) |
| 336 | |
| 337 | Return true if the object is an :term:`asynchronous generator iterator` |
| 338 | created by an :term:`asynchronous generator` function. |
| 339 | |
| 340 | .. versionadded:: 3.6 |
| 341 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 342 | .. function:: istraceback(object) |
| 343 | |
| 344 | Return true if the object is a traceback. |
| 345 | |
| 346 | |
| 347 | .. function:: isframe(object) |
| 348 | |
| 349 | Return true if the object is a frame. |
| 350 | |
| 351 | |
| 352 | .. function:: iscode(object) |
| 353 | |
| 354 | Return true if the object is a code. |
| 355 | |
| 356 | |
| 357 | .. function:: isbuiltin(object) |
| 358 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 359 | Return true if the object is a built-in function or a bound built-in method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 360 | |
| 361 | |
| 362 | .. function:: isroutine(object) |
| 363 | |
| 364 | Return true if the object is a user-defined or built-in function or method. |
| 365 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 366 | |
Christian Heimes | be5b30b | 2008-03-03 19:18:51 +0000 | [diff] [blame] | 367 | .. function:: isabstract(object) |
| 368 | |
| 369 | Return true if the object is an abstract base class. |
| 370 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 371 | |
| 372 | .. function:: ismethoddescriptor(object) |
| 373 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 374 | Return true if the object is a method descriptor, but not if |
| 375 | :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin` |
| 376 | are true. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 377 | |
Georg Brandl | e6bcc91 | 2008-05-12 18:05:20 +0000 | [diff] [blame] | 378 | This, for example, is true of ``int.__add__``. An object passing this test |
Martin Panter | bae5d81 | 2016-06-18 03:57:31 +0000 | [diff] [blame] | 379 | has a :meth:`~object.__get__` method but not a :meth:`~object.__set__` |
| 380 | method, but beyond that the set of attributes varies. A |
| 381 | :attr:`~definition.__name__` attribute is usually |
Georg Brandl | e6bcc91 | 2008-05-12 18:05:20 +0000 | [diff] [blame] | 382 | sensible, and :attr:`__doc__` often is. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 383 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 384 | Methods implemented via descriptors that also pass one of the other tests |
| 385 | return false from the :func:`ismethoddescriptor` test, simply because the |
| 386 | other tests promise more -- you can, e.g., count on having the |
Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 387 | :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 388 | |
| 389 | |
| 390 | .. function:: isdatadescriptor(object) |
| 391 | |
| 392 | Return true if the object is a data descriptor. |
| 393 | |
Martin Panter | bae5d81 | 2016-06-18 03:57:31 +0000 | [diff] [blame] | 394 | Data descriptors have both a :attr:`~object.__get__` and a :attr:`~object.__set__` method. |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 395 | Examples are properties (defined in Python), getsets, and members. The |
| 396 | latter two are defined in C and there are more specific tests available for |
| 397 | those types, which is robust across Python implementations. Typically, data |
Martin Panter | bae5d81 | 2016-06-18 03:57:31 +0000 | [diff] [blame] | 398 | descriptors will also have :attr:`~definition.__name__` and :attr:`__doc__` attributes |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 399 | (properties, getsets, and members have both of these attributes), but this is |
| 400 | not guaranteed. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 401 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 402 | |
| 403 | .. function:: isgetsetdescriptor(object) |
| 404 | |
| 405 | Return true if the object is a getset descriptor. |
| 406 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 407 | .. impl-detail:: |
| 408 | |
| 409 | getsets are attributes defined in extension modules via |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 410 | :c:type:`PyGetSetDef` structures. For Python implementations without such |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 411 | types, this method will always return ``False``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 412 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 413 | |
| 414 | .. function:: ismemberdescriptor(object) |
| 415 | |
| 416 | Return true if the object is a member descriptor. |
| 417 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 418 | .. impl-detail:: |
| 419 | |
| 420 | Member descriptors are attributes defined in extension modules via |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 421 | :c:type:`PyMemberDef` structures. For Python implementations without such |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 422 | types, this method will always return ``False``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 423 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 424 | |
| 425 | .. _inspect-source: |
| 426 | |
| 427 | Retrieving source code |
| 428 | ---------------------- |
| 429 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 430 | .. function:: getdoc(object) |
| 431 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 432 | Get the documentation string for an object, cleaned up with :func:`cleandoc`. |
Serhiy Storchaka | 5cf2b72 | 2015-04-03 22:38:53 +0300 | [diff] [blame] | 433 | If the documentation string for an object is not provided and the object is |
| 434 | a class, a method, a property or a descriptor, retrieve the documentation |
| 435 | string from the inheritance hierarchy. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 436 | |
Berker Peksag | 4333d8b | 2015-07-30 18:06:09 +0300 | [diff] [blame] | 437 | .. versionchanged:: 3.5 |
| 438 | Documentation strings are now inherited if not overridden. |
| 439 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 440 | |
| 441 | .. function:: getcomments(object) |
| 442 | |
| 443 | Return in a single string any lines of comments immediately preceding the |
| 444 | object's source code (for a class, function, or method), or at the top of the |
| 445 | Python source file (if the object is a module). |
| 446 | |
| 447 | |
| 448 | .. function:: getfile(object) |
| 449 | |
| 450 | Return the name of the (text or binary) file in which an object was defined. |
| 451 | This will fail with a :exc:`TypeError` if the object is a built-in module, |
| 452 | class, or function. |
| 453 | |
| 454 | |
| 455 | .. function:: getmodule(object) |
| 456 | |
| 457 | Try to guess which module an object was defined in. |
| 458 | |
| 459 | |
| 460 | .. function:: getsourcefile(object) |
| 461 | |
| 462 | Return the name of the Python source file in which an object was defined. This |
| 463 | will fail with a :exc:`TypeError` if the object is a built-in module, class, or |
| 464 | function. |
| 465 | |
| 466 | |
| 467 | .. function:: getsourcelines(object) |
| 468 | |
| 469 | Return a list of source lines and starting line number for an object. The |
| 470 | argument may be a module, class, method, function, traceback, frame, or code |
| 471 | object. The source code is returned as a list of the lines corresponding to the |
| 472 | object and the line number indicates where in the original source file the first |
Antoine Pitrou | 62ab10a0 | 2011-10-12 20:10:51 +0200 | [diff] [blame] | 473 | line of code was found. An :exc:`OSError` is raised if the source code cannot |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 474 | be retrieved. |
| 475 | |
Antoine Pitrou | 62ab10a0 | 2011-10-12 20:10:51 +0200 | [diff] [blame] | 476 | .. versionchanged:: 3.3 |
| 477 | :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the |
| 478 | former. |
| 479 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 480 | |
| 481 | .. function:: getsource(object) |
| 482 | |
| 483 | Return the text of the source code for an object. The argument may be a module, |
| 484 | class, method, function, traceback, frame, or code object. The source code is |
Antoine Pitrou | 62ab10a0 | 2011-10-12 20:10:51 +0200 | [diff] [blame] | 485 | returned as a single string. An :exc:`OSError` is raised if the source code |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 486 | cannot be retrieved. |
| 487 | |
Antoine Pitrou | 62ab10a0 | 2011-10-12 20:10:51 +0200 | [diff] [blame] | 488 | .. versionchanged:: 3.3 |
| 489 | :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the |
| 490 | former. |
| 491 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 492 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 493 | .. function:: cleandoc(doc) |
| 494 | |
| 495 | Clean up indentation from docstrings that are indented to line up with blocks |
Senthil Kumaran | ebd84e3 | 2016-05-29 20:36:58 -0700 | [diff] [blame] | 496 | of code. |
| 497 | |
| 498 | All leading whitespace is removed from the first line. Any leading whitespace |
| 499 | that can be uniformly removed from the second line onwards is removed. Empty |
| 500 | lines at the beginning and end are subsequently removed. Also, all tabs are |
| 501 | expanded to spaces. |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 502 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 503 | |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 504 | .. _inspect-signature-object: |
| 505 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 506 | Introspecting callables with the Signature object |
| 507 | ------------------------------------------------- |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 508 | |
| 509 | .. versionadded:: 3.3 |
| 510 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 511 | The Signature object represents the call signature of a callable object and its |
| 512 | return annotation. To retrieve a Signature object, use the :func:`signature` |
| 513 | function. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 514 | |
Yury Selivanov | bcd4fc1 | 2015-05-20 14:30:08 -0400 | [diff] [blame] | 515 | .. function:: signature(callable, \*, follow_wrapped=True) |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 516 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 517 | Return a :class:`Signature` object for the given ``callable``:: |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 518 | |
| 519 | >>> from inspect import signature |
| 520 | >>> def foo(a, *, b:int, **kwargs): |
| 521 | ... pass |
| 522 | |
| 523 | >>> sig = signature(foo) |
| 524 | |
| 525 | >>> str(sig) |
| 526 | '(a, *, b:int, **kwargs)' |
| 527 | |
| 528 | >>> str(sig.parameters['b']) |
| 529 | 'b:int' |
| 530 | |
| 531 | >>> sig.parameters['b'].annotation |
| 532 | <class 'int'> |
| 533 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 534 | Accepts a wide range of python callables, from plain functions and classes to |
| 535 | :func:`functools.partial` objects. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 536 | |
Larry Hastings | 5c66189 | 2014-01-24 06:17:25 -0800 | [diff] [blame] | 537 | Raises :exc:`ValueError` if no signature can be provided, and |
| 538 | :exc:`TypeError` if that type of object is not supported. |
| 539 | |
Yury Selivanov | bcd4fc1 | 2015-05-20 14:30:08 -0400 | [diff] [blame] | 540 | .. versionadded:: 3.5 |
| 541 | ``follow_wrapped`` parameter. Pass ``False`` to get a signature of |
| 542 | ``callable`` specifically (``callable.__wrapped__`` will not be used to |
| 543 | unwrap decorated callables.) |
| 544 | |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 545 | .. note:: |
| 546 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 547 | Some callables may not be introspectable in certain implementations of |
Yury Selivanov | d71e52f | 2014-01-30 00:22:57 -0500 | [diff] [blame] | 548 | Python. For example, in CPython, some built-in functions defined in |
| 549 | C provide no metadata about their arguments. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 550 | |
| 551 | |
Yury Selivanov | 7835689 | 2014-01-30 00:10:54 -0500 | [diff] [blame] | 552 | .. class:: Signature(parameters=None, \*, return_annotation=Signature.empty) |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 553 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 554 | A Signature object represents the call signature of a function and its return |
| 555 | annotation. For each parameter accepted by the function it stores a |
| 556 | :class:`Parameter` object in its :attr:`parameters` collection. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 557 | |
Yury Selivanov | 7835689 | 2014-01-30 00:10:54 -0500 | [diff] [blame] | 558 | The optional *parameters* argument is a sequence of :class:`Parameter` |
| 559 | objects, which is validated to check that there are no parameters with |
| 560 | duplicate names, and that the parameters are in the right order, i.e. |
| 561 | positional-only first, then positional-or-keyword, and that parameters with |
| 562 | defaults follow parameters without defaults. |
| 563 | |
| 564 | The optional *return_annotation* argument, can be an arbitrary Python object, |
| 565 | is the "return" annotation of the callable. |
| 566 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 567 | Signature objects are *immutable*. Use :meth:`Signature.replace` to make a |
| 568 | modified copy. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 569 | |
Yury Selivanov | 67d727e | 2014-03-29 13:24:14 -0400 | [diff] [blame] | 570 | .. versionchanged:: 3.5 |
Yury Selivanov | 67ae50e | 2014-04-08 11:46:50 -0400 | [diff] [blame] | 571 | Signature objects are picklable and hashable. |
Yury Selivanov | 67d727e | 2014-03-29 13:24:14 -0400 | [diff] [blame] | 572 | |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 573 | .. attribute:: Signature.empty |
| 574 | |
| 575 | A special class-level marker to specify absence of a return annotation. |
| 576 | |
| 577 | .. attribute:: Signature.parameters |
| 578 | |
| 579 | An ordered mapping of parameters' names to the corresponding |
| 580 | :class:`Parameter` objects. |
| 581 | |
| 582 | .. attribute:: Signature.return_annotation |
| 583 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 584 | The "return" annotation for the callable. If the callable has no "return" |
| 585 | annotation, this attribute is set to :attr:`Signature.empty`. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 586 | |
| 587 | .. method:: Signature.bind(*args, **kwargs) |
| 588 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 589 | Create a mapping from positional and keyword arguments to parameters. |
| 590 | Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the |
| 591 | signature, or raises a :exc:`TypeError`. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 592 | |
| 593 | .. method:: Signature.bind_partial(*args, **kwargs) |
| 594 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 595 | Works the same way as :meth:`Signature.bind`, but allows the omission of |
| 596 | some required arguments (mimics :func:`functools.partial` behavior.) |
| 597 | Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the |
| 598 | passed arguments do not match the signature. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 599 | |
Ezio Melotti | 8429b67 | 2012-09-14 06:35:09 +0300 | [diff] [blame] | 600 | .. method:: Signature.replace(*[, parameters][, return_annotation]) |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 601 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 602 | Create a new Signature instance based on the instance replace was invoked |
| 603 | on. It is possible to pass different ``parameters`` and/or |
| 604 | ``return_annotation`` to override the corresponding properties of the base |
| 605 | signature. To remove return_annotation from the copied Signature, pass in |
| 606 | :attr:`Signature.empty`. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 607 | |
| 608 | :: |
| 609 | |
| 610 | >>> def test(a, b): |
| 611 | ... pass |
| 612 | >>> sig = signature(test) |
| 613 | >>> new_sig = sig.replace(return_annotation="new return anno") |
| 614 | >>> str(new_sig) |
| 615 | "(a, b) -> 'new return anno'" |
| 616 | |
Yury Selivanov | bcd4fc1 | 2015-05-20 14:30:08 -0400 | [diff] [blame] | 617 | .. classmethod:: Signature.from_callable(obj, \*, follow_wrapped=True) |
Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 618 | |
| 619 | Return a :class:`Signature` (or its subclass) object for a given callable |
Yury Selivanov | bcd4fc1 | 2015-05-20 14:30:08 -0400 | [diff] [blame] | 620 | ``obj``. Pass ``follow_wrapped=False`` to get a signature of ``obj`` |
| 621 | without unwrapping its ``__wrapped__`` chain. |
Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 622 | |
Yury Selivanov | bcd4fc1 | 2015-05-20 14:30:08 -0400 | [diff] [blame] | 623 | This method simplifies subclassing of :class:`Signature`:: |
Yury Selivanov | da39645 | 2014-03-27 12:09:24 -0400 | [diff] [blame] | 624 | |
| 625 | class MySignature(Signature): |
| 626 | pass |
| 627 | sig = MySignature.from_callable(min) |
| 628 | assert isinstance(sig, MySignature) |
| 629 | |
Yury Selivanov | 232b934 | 2014-03-29 13:18:30 -0400 | [diff] [blame] | 630 | .. versionadded:: 3.5 |
| 631 | |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 632 | |
Yury Selivanov | 7835689 | 2014-01-30 00:10:54 -0500 | [diff] [blame] | 633 | .. class:: Parameter(name, kind, \*, default=Parameter.empty, annotation=Parameter.empty) |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 634 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 635 | Parameter objects are *immutable*. Instead of modifying a Parameter object, |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 636 | you can use :meth:`Parameter.replace` to create a modified copy. |
| 637 | |
Yury Selivanov | 67d727e | 2014-03-29 13:24:14 -0400 | [diff] [blame] | 638 | .. versionchanged:: 3.5 |
Yury Selivanov | 67ae50e | 2014-04-08 11:46:50 -0400 | [diff] [blame] | 639 | Parameter objects are picklable and hashable. |
Yury Selivanov | 67d727e | 2014-03-29 13:24:14 -0400 | [diff] [blame] | 640 | |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 641 | .. attribute:: Parameter.empty |
| 642 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 643 | A special class-level marker to specify absence of default values and |
| 644 | annotations. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 645 | |
| 646 | .. attribute:: Parameter.name |
| 647 | |
Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 648 | The name of the parameter as a string. The name must be a valid |
| 649 | Python identifier. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 650 | |
Nick Coghlan | b4b966e | 2016-06-04 14:40:03 -0700 | [diff] [blame] | 651 | .. impl-detail:: |
| 652 | |
| 653 | CPython generates implicit parameter names of the form ``.0`` on the |
| 654 | code objects used to implement comprehensions and generator |
| 655 | expressions. |
| 656 | |
| 657 | .. versionchanged:: 3.6 |
| 658 | These parameter names are exposed by this module as names like |
| 659 | ``implicit0``. |
| 660 | |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 661 | .. attribute:: Parameter.default |
| 662 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 663 | The default value for the parameter. If the parameter has no default |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 664 | value, this attribute is set to :attr:`Parameter.empty`. |
| 665 | |
| 666 | .. attribute:: Parameter.annotation |
| 667 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 668 | The annotation for the parameter. If the parameter has no annotation, |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 669 | this attribute is set to :attr:`Parameter.empty`. |
| 670 | |
| 671 | .. attribute:: Parameter.kind |
| 672 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 673 | Describes how argument values are bound to the parameter. Possible values |
| 674 | (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``): |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 675 | |
Georg Brandl | 44ea77b | 2013-03-28 13:28:44 +0100 | [diff] [blame] | 676 | .. tabularcolumns:: |l|L| |
| 677 | |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 678 | +------------------------+----------------------------------------------+ |
| 679 | | Name | Meaning | |
| 680 | +========================+==============================================+ |
| 681 | | *POSITIONAL_ONLY* | Value must be supplied as a positional | |
| 682 | | | argument. | |
| 683 | | | | |
| 684 | | | Python has no explicit syntax for defining | |
| 685 | | | positional-only parameters, but many built-in| |
| 686 | | | and extension module functions (especially | |
| 687 | | | those that accept only one or two parameters)| |
| 688 | | | accept them. | |
| 689 | +------------------------+----------------------------------------------+ |
| 690 | | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or | |
| 691 | | | positional argument (this is the standard | |
| 692 | | | binding behaviour for functions implemented | |
| 693 | | | in Python.) | |
| 694 | +------------------------+----------------------------------------------+ |
| 695 | | *VAR_POSITIONAL* | A tuple of positional arguments that aren't | |
| 696 | | | bound to any other parameter. This | |
| 697 | | | corresponds to a ``*args`` parameter in a | |
| 698 | | | Python function definition. | |
| 699 | +------------------------+----------------------------------------------+ |
| 700 | | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.| |
| 701 | | | Keyword only parameters are those which | |
| 702 | | | appear after a ``*`` or ``*args`` entry in a | |
| 703 | | | Python function definition. | |
| 704 | +------------------------+----------------------------------------------+ |
| 705 | | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound| |
| 706 | | | to any other parameter. This corresponds to a| |
| 707 | | | ``**kwargs`` parameter in a Python function | |
| 708 | | | definition. | |
| 709 | +------------------------+----------------------------------------------+ |
| 710 | |
Andrew Svetlov | eed1808 | 2012-08-13 18:23:54 +0300 | [diff] [blame] | 711 | Example: print all keyword-only arguments without default values:: |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 712 | |
| 713 | >>> def foo(a, b, *, c, d=10): |
| 714 | ... pass |
| 715 | |
| 716 | >>> sig = signature(foo) |
| 717 | >>> for param in sig.parameters.values(): |
| 718 | ... if (param.kind == param.KEYWORD_ONLY and |
| 719 | ... param.default is param.empty): |
| 720 | ... print('Parameter:', param) |
| 721 | Parameter: c |
| 722 | |
Ezio Melotti | 8429b67 | 2012-09-14 06:35:09 +0300 | [diff] [blame] | 723 | .. method:: Parameter.replace(*[, name][, kind][, default][, annotation]) |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 724 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 725 | Create a new Parameter instance based on the instance replaced was invoked |
| 726 | on. To override a :class:`Parameter` attribute, pass the corresponding |
| 727 | argument. To remove a default value or/and an annotation from a |
| 728 | Parameter, pass :attr:`Parameter.empty`. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 729 | |
| 730 | :: |
| 731 | |
| 732 | >>> from inspect import Parameter |
| 733 | >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42) |
| 734 | >>> str(param) |
| 735 | 'foo=42' |
| 736 | |
| 737 | >>> str(param.replace()) # Will create a shallow copy of 'param' |
| 738 | 'foo=42' |
| 739 | |
| 740 | >>> str(param.replace(default=Parameter.empty, annotation='spam')) |
| 741 | "foo:'spam'" |
| 742 | |
Yury Selivanov | 2393dca | 2014-01-27 15:07:58 -0500 | [diff] [blame] | 743 | .. versionchanged:: 3.4 |
| 744 | In Python 3.3 Parameter objects were allowed to have ``name`` set |
| 745 | to ``None`` if their ``kind`` was set to ``POSITIONAL_ONLY``. |
| 746 | This is no longer permitted. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 747 | |
| 748 | .. class:: BoundArguments |
| 749 | |
| 750 | Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call. |
| 751 | Holds the mapping of arguments to the function's parameters. |
| 752 | |
| 753 | .. attribute:: BoundArguments.arguments |
| 754 | |
| 755 | An ordered, mutable mapping (:class:`collections.OrderedDict`) of |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 756 | parameters' names to arguments' values. Contains only explicitly bound |
| 757 | arguments. Changes in :attr:`arguments` will reflect in :attr:`args` and |
| 758 | :attr:`kwargs`. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 759 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 760 | Should be used in conjunction with :attr:`Signature.parameters` for any |
| 761 | argument processing purposes. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 762 | |
| 763 | .. note:: |
| 764 | |
| 765 | Arguments for which :meth:`Signature.bind` or |
| 766 | :meth:`Signature.bind_partial` relied on a default value are skipped. |
Yury Selivanov | b907a51 | 2015-05-16 13:45:09 -0400 | [diff] [blame] | 767 | However, if needed, use :meth:`BoundArguments.apply_defaults` to add |
| 768 | them. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 769 | |
| 770 | .. attribute:: BoundArguments.args |
| 771 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 772 | A tuple of positional arguments values. Dynamically computed from the |
| 773 | :attr:`arguments` attribute. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 774 | |
| 775 | .. attribute:: BoundArguments.kwargs |
| 776 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 777 | A dict of keyword arguments values. Dynamically computed from the |
| 778 | :attr:`arguments` attribute. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 779 | |
Yury Selivanov | 8279619 | 2015-05-14 14:14:02 -0400 | [diff] [blame] | 780 | .. attribute:: BoundArguments.signature |
| 781 | |
| 782 | A reference to the parent :class:`Signature` object. |
| 783 | |
Yury Selivanov | b907a51 | 2015-05-16 13:45:09 -0400 | [diff] [blame] | 784 | .. method:: BoundArguments.apply_defaults() |
| 785 | |
| 786 | Set default values for missing arguments. |
| 787 | |
| 788 | For variable-positional arguments (``*args``) the default is an |
| 789 | empty tuple. |
| 790 | |
| 791 | For variable-keyword arguments (``**kwargs``) the default is an |
| 792 | empty dict. |
| 793 | |
| 794 | :: |
| 795 | |
| 796 | >>> def foo(a, b='ham', *args): pass |
| 797 | >>> ba = inspect.signature(foo).bind('spam') |
| 798 | >>> ba.apply_defaults() |
| 799 | >>> ba.arguments |
| 800 | OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())]) |
| 801 | |
Berker Peksag | 5b3df5b | 2015-05-16 23:29:31 +0300 | [diff] [blame] | 802 | .. versionadded:: 3.5 |
| 803 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 804 | The :attr:`args` and :attr:`kwargs` properties can be used to invoke |
| 805 | functions:: |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 806 | |
| 807 | def test(a, *, b): |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 808 | ... |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 809 | |
| 810 | sig = signature(test) |
| 811 | ba = sig.bind(10, b=20) |
| 812 | test(*ba.args, **ba.kwargs) |
| 813 | |
| 814 | |
Georg Brandl | e471772 | 2012-08-14 09:45:28 +0200 | [diff] [blame] | 815 | .. seealso:: |
| 816 | |
| 817 | :pep:`362` - Function Signature Object. |
| 818 | The detailed specification, implementation details and examples. |
| 819 | |
| 820 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 821 | .. _inspect-classes-functions: |
| 822 | |
| 823 | Classes and functions |
| 824 | --------------------- |
| 825 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 826 | .. function:: getclasstree(classes, unique=False) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 827 | |
| 828 | Arrange the given list of classes into a hierarchy of nested lists. Where a |
| 829 | nested list appears, it contains classes derived from the class whose entry |
| 830 | immediately precedes the list. Each entry is a 2-tuple containing a class and a |
| 831 | tuple of its base classes. If the *unique* argument is true, exactly one entry |
| 832 | appears in the returned structure for each class in the given list. Otherwise, |
| 833 | classes using multiple inheritance and their descendants will appear multiple |
| 834 | times. |
| 835 | |
Yury Selivanov | 37dc2b2 | 2016-01-11 15:15:01 -0500 | [diff] [blame] | 836 | |
| 837 | .. function:: getargspec(func) |
| 838 | |
Nick Coghlan | 3c35fdb | 2016-12-02 20:29:57 +1000 | [diff] [blame] | 839 | Get the names and default values of a Python function's parameters. A |
Yury Selivanov | 37dc2b2 | 2016-01-11 15:15:01 -0500 | [diff] [blame] | 840 | :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is |
Nick Coghlan | 3c35fdb | 2016-12-02 20:29:57 +1000 | [diff] [blame] | 841 | returned. *args* is a list of the parameter names. *varargs* and *keywords* |
| 842 | are the names of the ``*`` and ``**`` parameters or ``None``. *defaults* is a |
Yury Selivanov | 37dc2b2 | 2016-01-11 15:15:01 -0500 | [diff] [blame] | 843 | tuple of default argument values or ``None`` if there are no default |
| 844 | arguments; if this tuple has *n* elements, they correspond to the last |
| 845 | *n* elements listed in *args*. |
| 846 | |
| 847 | .. deprecated:: 3.0 |
Nick Coghlan | 3c35fdb | 2016-12-02 20:29:57 +1000 | [diff] [blame] | 848 | Use :func:`getfullargspec` for an updated API that is usually a drop-in |
| 849 | replacement, but also correctly handles function annotations and |
| 850 | keyword-only parameters. |
| 851 | |
| 852 | Alternatively, use :func:`signature` and |
Yury Selivanov | 37dc2b2 | 2016-01-11 15:15:01 -0500 | [diff] [blame] | 853 | :ref:`Signature Object <inspect-signature-object>`, which provide a |
Nick Coghlan | 3c35fdb | 2016-12-02 20:29:57 +1000 | [diff] [blame] | 854 | more structured introspection API for callables. |
Yury Selivanov | 37dc2b2 | 2016-01-11 15:15:01 -0500 | [diff] [blame] | 855 | |
| 856 | |
Georg Brandl | 138bcb5 | 2007-09-12 19:04:21 +0000 | [diff] [blame] | 857 | .. function:: getfullargspec(func) |
| 858 | |
Nick Coghlan | 3c35fdb | 2016-12-02 20:29:57 +1000 | [diff] [blame] | 859 | Get the names and default values of a Python function's parameters. A |
Georg Brandl | 8240275 | 2010-01-09 09:48:46 +0000 | [diff] [blame] | 860 | :term:`named tuple` is returned: |
Georg Brandl | 138bcb5 | 2007-09-12 19:04:21 +0000 | [diff] [blame] | 861 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 862 | ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, |
| 863 | annotations)`` |
Georg Brandl | 138bcb5 | 2007-09-12 19:04:21 +0000 | [diff] [blame] | 864 | |
Nick Coghlan | 3c35fdb | 2016-12-02 20:29:57 +1000 | [diff] [blame] | 865 | *args* is a list of the positional parameter names. |
| 866 | *varargs* is the name of the ``*`` parameter or ``None`` if arbitrary |
| 867 | positional arguments are not accepted. |
| 868 | *varkw* is the name of the ``**`` parameter or ``None`` if arbitrary |
| 869 | keyword arguments are not accepted. |
| 870 | *defaults* is an *n*-tuple of default argument values corresponding to the |
| 871 | last *n* positional parameters, or ``None`` if there are no such defaults |
| 872 | defined. |
| 873 | *kwonlyargs* is a list of keyword-only parameter names. |
| 874 | *kwonlydefaults* is a dictionary mapping parameter names from *kwonlyargs* |
| 875 | to the default values used if no argument is supplied. |
| 876 | *annotations* is a dictionary mapping parameter names to annotations. |
| 877 | The special key ``"return"`` is used to report the function return value |
| 878 | annotation (if any). |
| 879 | |
| 880 | Note that :func:`signature` and |
| 881 | :ref:`Signature Object <inspect-signature-object>` provide the recommended |
| 882 | API for callable introspection, and support additional behaviours (like |
| 883 | positional-only arguments) that are sometimes encountered in extension module |
| 884 | APIs. This function is retained primarily for use in code that needs to |
| 885 | maintain compatibility with the Python 2 ``inspect`` module API. |
Georg Brandl | 138bcb5 | 2007-09-12 19:04:21 +0000 | [diff] [blame] | 886 | |
Nick Coghlan | 1635578 | 2014-03-08 16:36:37 +1000 | [diff] [blame] | 887 | .. versionchanged:: 3.4 |
| 888 | This function is now based on :func:`signature`, but still ignores |
| 889 | ``__wrapped__`` attributes and includes the already bound first |
| 890 | parameter in the signature output for bound methods. |
| 891 | |
Nick Coghlan | 3c35fdb | 2016-12-02 20:29:57 +1000 | [diff] [blame] | 892 | .. versionchanged:: 3.6 |
| 893 | This method was previously documented as deprecated in favour of |
| 894 | :func:`signature` in Python 3.5, but that decision has been reversed |
| 895 | in order to restore a clearly supported standard interface for |
| 896 | single-source Python 2/3 code migrating away from the legacy |
| 897 | :func:`getargspec` API. |
Yury Selivanov | 3cfec2e | 2015-05-22 11:38:38 -0400 | [diff] [blame] | 898 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 899 | |
| 900 | .. function:: getargvalues(frame) |
| 901 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 902 | Get information about arguments passed into a particular frame. A |
| 903 | :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is |
Georg Brandl | b30f330 | 2011-01-06 09:23:56 +0000 | [diff] [blame] | 904 | returned. *args* is a list of the argument names. *varargs* and *keywords* |
| 905 | are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 906 | locals dictionary of the given frame. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 907 | |
Berker Peksag | 2197eac | 2017-02-23 18:42:30 +0300 | [diff] [blame^] | 908 | .. note:: |
| 909 | This function was inadvertently marked as deprecated in Python 3.5. |
Yury Selivanov | 945fff4 | 2015-05-22 16:28:05 -0400 | [diff] [blame] | 910 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 911 | |
Andrew Svetlov | 735d317 | 2012-10-27 00:28:20 +0300 | [diff] [blame] | 912 | .. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 913 | |
Michael Foord | 3af125a | 2012-04-21 18:22:28 +0100 | [diff] [blame] | 914 | Format a pretty argument spec from the values returned by |
Berker Peksag | fa3922c | 2015-07-31 04:11:29 +0300 | [diff] [blame] | 915 | :func:`getfullargspec`. |
Michael Foord | 3af125a | 2012-04-21 18:22:28 +0100 | [diff] [blame] | 916 | |
| 917 | The first seven arguments are (``args``, ``varargs``, ``varkw``, |
Georg Brandl | 8ed75cd | 2014-10-31 10:25:48 +0100 | [diff] [blame] | 918 | ``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``). |
Andrew Svetlov | 735d317 | 2012-10-27 00:28:20 +0300 | [diff] [blame] | 919 | |
Georg Brandl | 8ed75cd | 2014-10-31 10:25:48 +0100 | [diff] [blame] | 920 | The other six arguments are functions that are called to turn argument names, |
| 921 | ``*`` argument name, ``**`` argument name, default values, return annotation |
| 922 | and individual annotations into strings, respectively. |
| 923 | |
| 924 | For example: |
| 925 | |
| 926 | >>> from inspect import formatargspec, getfullargspec |
| 927 | >>> def f(a: int, b: float): |
| 928 | ... pass |
| 929 | ... |
| 930 | >>> formatargspec(*getfullargspec(f)) |
| 931 | '(a: int, b: float)' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 932 | |
Yury Selivanov | 945fff4 | 2015-05-22 16:28:05 -0400 | [diff] [blame] | 933 | .. deprecated:: 3.5 |
| 934 | Use :func:`signature` and |
| 935 | :ref:`Signature Object <inspect-signature-object>`, which provide a |
| 936 | better introspecting API for callables. |
| 937 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 938 | |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 939 | .. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 940 | |
| 941 | Format a pretty argument spec from the four values returned by |
| 942 | :func:`getargvalues`. The format\* arguments are the corresponding optional |
| 943 | formatting functions that are called to turn names and values into strings. |
| 944 | |
Berker Peksag | 2197eac | 2017-02-23 18:42:30 +0300 | [diff] [blame^] | 945 | .. note:: |
| 946 | This function was inadvertently marked as deprecated in Python 3.5. |
Yury Selivanov | 945fff4 | 2015-05-22 16:28:05 -0400 | [diff] [blame] | 947 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 948 | |
| 949 | .. function:: getmro(cls) |
| 950 | |
| 951 | Return a tuple of class cls's base classes, including cls, in method resolution |
| 952 | order. No class appears more than once in this tuple. Note that the method |
| 953 | resolution order depends on cls's type. Unless a very peculiar user-defined |
| 954 | metatype is in use, cls will be the first element of the tuple. |
| 955 | |
| 956 | |
Benjamin Peterson | 3a990c6 | 2014-01-02 12:22:30 -0600 | [diff] [blame] | 957 | .. function:: getcallargs(func, *args, **kwds) |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 958 | |
| 959 | Bind the *args* and *kwds* to the argument names of the Python function or |
| 960 | method *func*, as if it was called with them. For bound methods, bind also the |
| 961 | first argument (typically named ``self``) to the associated instance. A dict |
| 962 | is returned, mapping the argument names (including the names of the ``*`` and |
| 963 | ``**`` arguments, if any) to their values from *args* and *kwds*. In case of |
| 964 | invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise |
| 965 | an exception because of incompatible signature, an exception of the same type |
| 966 | and the same or similar message is raised. For example:: |
| 967 | |
| 968 | >>> from inspect import getcallargs |
| 969 | >>> def f(a, b=1, *pos, **named): |
| 970 | ... pass |
Andrew Svetlov | e939f38 | 2012-08-09 13:25:32 +0300 | [diff] [blame] | 971 | >>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)} |
| 972 | True |
| 973 | >>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()} |
| 974 | True |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 975 | >>> getcallargs(f) |
| 976 | Traceback (most recent call last): |
| 977 | ... |
Andrew Svetlov | e939f38 | 2012-08-09 13:25:32 +0300 | [diff] [blame] | 978 | TypeError: f() missing 1 required positional argument: 'a' |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 979 | |
| 980 | .. versionadded:: 3.2 |
| 981 | |
Yury Selivanov | 3cfec2e | 2015-05-22 11:38:38 -0400 | [diff] [blame] | 982 | .. deprecated:: 3.5 |
| 983 | Use :meth:`Signature.bind` and :meth:`Signature.bind_partial` instead. |
Andrew Svetlov | 4e48bf9 | 2012-08-13 17:10:28 +0300 | [diff] [blame] | 984 | |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 985 | |
Nick Coghlan | 2f92e54 | 2012-06-23 19:39:55 +1000 | [diff] [blame] | 986 | .. function:: getclosurevars(func) |
| 987 | |
| 988 | Get the mapping of external name references in a Python function or |
| 989 | method *func* to their current values. A |
| 990 | :term:`named tuple` ``ClosureVars(nonlocals, globals, builtins, unbound)`` |
| 991 | is returned. *nonlocals* maps referenced names to lexical closure |
| 992 | variables, *globals* to the function's module globals and *builtins* to |
| 993 | the builtins visible from the function body. *unbound* is the set of names |
| 994 | referenced in the function that could not be resolved at all given the |
| 995 | current module globals and builtins. |
| 996 | |
| 997 | :exc:`TypeError` is raised if *func* is not a Python function or method. |
| 998 | |
| 999 | .. versionadded:: 3.3 |
| 1000 | |
| 1001 | |
Nick Coghlan | e8c45d6 | 2013-07-28 20:00:01 +1000 | [diff] [blame] | 1002 | .. function:: unwrap(func, *, stop=None) |
| 1003 | |
| 1004 | Get the object wrapped by *func*. It follows the chain of :attr:`__wrapped__` |
| 1005 | attributes returning the last object in the chain. |
| 1006 | |
| 1007 | *stop* is an optional callback accepting an object in the wrapper chain |
| 1008 | as its sole argument that allows the unwrapping to be terminated early if |
| 1009 | the callback returns a true value. If the callback never returns a true |
| 1010 | value, the last object in the chain is returned as usual. For example, |
| 1011 | :func:`signature` uses this to stop unwrapping if any object in the |
| 1012 | chain has a ``__signature__`` attribute defined. |
| 1013 | |
| 1014 | :exc:`ValueError` is raised if a cycle is encountered. |
| 1015 | |
| 1016 | .. versionadded:: 3.4 |
| 1017 | |
| 1018 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1019 | .. _inspect-stack: |
| 1020 | |
| 1021 | The interpreter stack |
| 1022 | --------------------- |
| 1023 | |
Antoine Pitrou | cdcafb7 | 2014-08-24 10:50:28 -0400 | [diff] [blame] | 1024 | When the following functions return "frame records," each record is a |
| 1025 | :term:`named tuple` |
| 1026 | ``FrameInfo(frame, filename, lineno, function, code_context, index)``. |
| 1027 | The tuple contains the frame object, the filename, the line number of the |
| 1028 | current line, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1029 | the function name, a list of lines of context from the source code, and the |
| 1030 | index of the current line within that list. |
| 1031 | |
Antoine Pitrou | cdcafb7 | 2014-08-24 10:50:28 -0400 | [diff] [blame] | 1032 | .. versionchanged:: 3.5 |
| 1033 | Return a named tuple instead of a tuple. |
| 1034 | |
Georg Brandl | e720c0a | 2009-04-27 16:20:50 +0000 | [diff] [blame] | 1035 | .. note:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1036 | |
| 1037 | Keeping references to frame objects, as found in the first element of the frame |
| 1038 | records these functions return, can cause your program to create reference |
| 1039 | cycles. Once a reference cycle has been created, the lifespan of all objects |
| 1040 | which can be accessed from the objects which form the cycle can become much |
| 1041 | longer even if Python's optional cycle detector is enabled. If such cycles must |
| 1042 | be created, it is important to ensure they are explicitly broken to avoid the |
| 1043 | delayed destruction of objects and increased memory consumption which occurs. |
| 1044 | |
| 1045 | Though the cycle detector will catch these, destruction of the frames (and local |
| 1046 | variables) can be made deterministic by removing the cycle in a |
| 1047 | :keyword:`finally` clause. This is also important if the cycle detector was |
| 1048 | disabled when Python was compiled or using :func:`gc.disable`. For example:: |
| 1049 | |
| 1050 | def handle_stackframe_without_leak(): |
| 1051 | frame = inspect.currentframe() |
| 1052 | try: |
| 1053 | # do something with the frame |
| 1054 | finally: |
| 1055 | del frame |
| 1056 | |
Antoine Pitrou | 58720d6 | 2013-08-05 23:26:40 +0200 | [diff] [blame] | 1057 | If you want to keep the frame around (for example to print a traceback |
| 1058 | later), you can also break reference cycles by using the |
| 1059 | :meth:`frame.clear` method. |
| 1060 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1061 | The optional *context* argument supported by most of these functions specifies |
| 1062 | the number of lines of context to return, which are centered around the current |
| 1063 | line. |
| 1064 | |
| 1065 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 1066 | .. function:: getframeinfo(frame, context=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1067 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1068 | Get information about a frame or traceback object. A :term:`named tuple` |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 1069 | ``Traceback(filename, lineno, function, code_context, index)`` is returned. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1070 | |
| 1071 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 1072 | .. function:: getouterframes(frame, context=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1073 | |
| 1074 | Get a list of frame records for a frame and all outer frames. These frames |
| 1075 | represent the calls that lead to the creation of *frame*. The first entry in the |
| 1076 | returned list represents *frame*; the last entry represents the outermost call |
| 1077 | on *frame*'s stack. |
| 1078 | |
Yury Selivanov | 100fc3f | 2015-09-08 22:40:30 -0400 | [diff] [blame] | 1079 | .. versionchanged:: 3.5 |
| 1080 | A list of :term:`named tuples <named tuple>` |
| 1081 | ``FrameInfo(frame, filename, lineno, function, code_context, index)`` |
| 1082 | is returned. |
| 1083 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1084 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 1085 | .. function:: getinnerframes(traceback, context=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1086 | |
| 1087 | Get a list of frame records for a traceback's frame and all inner frames. These |
| 1088 | frames represent calls made as a consequence of *frame*. The first entry in the |
| 1089 | list represents *traceback*; the last entry represents where the exception was |
| 1090 | raised. |
| 1091 | |
Yury Selivanov | 100fc3f | 2015-09-08 22:40:30 -0400 | [diff] [blame] | 1092 | .. versionchanged:: 3.5 |
| 1093 | A list of :term:`named tuples <named tuple>` |
| 1094 | ``FrameInfo(frame, filename, lineno, function, code_context, index)`` |
| 1095 | is returned. |
| 1096 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1097 | |
| 1098 | .. function:: currentframe() |
| 1099 | |
| 1100 | Return the frame object for the caller's stack frame. |
| 1101 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 1102 | .. impl-detail:: |
| 1103 | |
| 1104 | This function relies on Python stack frame support in the interpreter, |
| 1105 | which isn't guaranteed to exist in all implementations of Python. If |
| 1106 | running in an implementation without Python stack frame support this |
| 1107 | function returns ``None``. |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 1108 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1109 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 1110 | .. function:: stack(context=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1111 | |
| 1112 | Return a list of frame records for the caller's stack. The first entry in the |
| 1113 | returned list represents the caller; the last entry represents the outermost |
| 1114 | call on the stack. |
| 1115 | |
Yury Selivanov | 100fc3f | 2015-09-08 22:40:30 -0400 | [diff] [blame] | 1116 | .. versionchanged:: 3.5 |
| 1117 | A list of :term:`named tuples <named tuple>` |
| 1118 | ``FrameInfo(frame, filename, lineno, function, code_context, index)`` |
| 1119 | is returned. |
| 1120 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1121 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 1122 | .. function:: trace(context=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1123 | |
| 1124 | Return a list of frame records for the stack between the current frame and the |
| 1125 | frame in which an exception currently being handled was raised in. The first |
| 1126 | entry in the list represents the caller; the last entry represents where the |
| 1127 | exception was raised. |
| 1128 | |
Yury Selivanov | 100fc3f | 2015-09-08 22:40:30 -0400 | [diff] [blame] | 1129 | .. versionchanged:: 3.5 |
| 1130 | A list of :term:`named tuples <named tuple>` |
| 1131 | ``FrameInfo(frame, filename, lineno, function, code_context, index)`` |
| 1132 | is returned. |
| 1133 | |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1134 | |
| 1135 | Fetching attributes statically |
| 1136 | ------------------------------ |
| 1137 | |
| 1138 | Both :func:`getattr` and :func:`hasattr` can trigger code execution when |
| 1139 | fetching or checking for the existence of attributes. Descriptors, like |
| 1140 | properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__` |
| 1141 | may be called. |
| 1142 | |
| 1143 | For cases where you want passive introspection, like documentation tools, this |
Éric Araujo | 941afed | 2011-09-01 02:47:34 +0200 | [diff] [blame] | 1144 | can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr` |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1145 | but avoids executing code when it fetches attributes. |
| 1146 | |
| 1147 | .. function:: getattr_static(obj, attr, default=None) |
| 1148 | |
| 1149 | Retrieve attributes without triggering dynamic lookup via the |
Éric Araujo | 941afed | 2011-09-01 02:47:34 +0200 | [diff] [blame] | 1150 | descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`. |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1151 | |
| 1152 | Note: this function may not be able to retrieve all attributes |
| 1153 | that getattr can fetch (like dynamically created attributes) |
| 1154 | and may find attributes that getattr can't (like descriptors |
| 1155 | that raise AttributeError). It can also return descriptors objects |
| 1156 | instead of instance members. |
| 1157 | |
Serhiy Storchaka | bfdcd43 | 2013-10-13 23:09:14 +0300 | [diff] [blame] | 1158 | If the instance :attr:`~object.__dict__` is shadowed by another member (for |
| 1159 | example a property) then this function will be unable to find instance |
| 1160 | members. |
Nick Coghlan | 2dad5ca | 2010-11-21 03:55:53 +0000 | [diff] [blame] | 1161 | |
Michael Foord | dcebe0f | 2011-03-15 19:20:44 -0400 | [diff] [blame] | 1162 | .. versionadded:: 3.2 |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1163 | |
Éric Araujo | 941afed | 2011-09-01 02:47:34 +0200 | [diff] [blame] | 1164 | :func:`getattr_static` does not resolve descriptors, for example slot descriptors or |
Michael Foord | e516265 | 2010-11-20 16:40:44 +0000 | [diff] [blame] | 1165 | getset descriptors on objects implemented in C. The descriptor object |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1166 | is returned instead of the underlying attribute. |
| 1167 | |
| 1168 | You can handle these with code like the following. Note that |
| 1169 | for arbitrary getset descriptors invoking these may trigger |
| 1170 | code execution:: |
| 1171 | |
| 1172 | # example code for resolving the builtin descriptor types |
Éric Araujo | 28053fb | 2010-11-22 03:09:19 +0000 | [diff] [blame] | 1173 | class _foo: |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 1174 | __slots__ = ['foo'] |
| 1175 | |
| 1176 | slot_descriptor = type(_foo.foo) |
| 1177 | getset_descriptor = type(type(open(__file__)).name) |
| 1178 | wrapper_descriptor = type(str.__dict__['__add__']) |
| 1179 | descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor) |
| 1180 | |
| 1181 | result = getattr_static(some_object, 'foo') |
| 1182 | if type(result) in descriptor_types: |
| 1183 | try: |
| 1184 | result = result.__get__() |
| 1185 | except AttributeError: |
| 1186 | # descriptors can raise AttributeError to |
| 1187 | # indicate there is no underlying value |
| 1188 | # in which case the descriptor itself will |
| 1189 | # have to do |
| 1190 | pass |
Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 1191 | |
Nick Coghlan | 2dad5ca | 2010-11-21 03:55:53 +0000 | [diff] [blame] | 1192 | |
Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 1193 | Current State of Generators and Coroutines |
| 1194 | ------------------------------------------ |
Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 1195 | |
| 1196 | When implementing coroutine schedulers and for other advanced uses of |
| 1197 | generators, it is useful to determine whether a generator is currently |
| 1198 | executing, is waiting to start or resume or execution, or has already |
Raymond Hettinger | 48f3bd3 | 2010-12-16 00:30:53 +0000 | [diff] [blame] | 1199 | terminated. :func:`getgeneratorstate` allows the current state of a |
Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 1200 | generator to be determined easily. |
| 1201 | |
| 1202 | .. function:: getgeneratorstate(generator) |
| 1203 | |
Raymond Hettinger | 48f3bd3 | 2010-12-16 00:30:53 +0000 | [diff] [blame] | 1204 | Get current state of a generator-iterator. |
Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 1205 | |
Raymond Hettinger | 48f3bd3 | 2010-12-16 00:30:53 +0000 | [diff] [blame] | 1206 | Possible states are: |
Raymond Hettinger | a275c98 | 2011-01-20 04:03:19 +0000 | [diff] [blame] | 1207 | * GEN_CREATED: Waiting to start execution. |
| 1208 | * GEN_RUNNING: Currently being executed by the interpreter. |
| 1209 | * GEN_SUSPENDED: Currently suspended at a yield expression. |
| 1210 | * GEN_CLOSED: Execution has completed. |
Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 1211 | |
Nick Coghlan | 2dad5ca | 2010-11-21 03:55:53 +0000 | [diff] [blame] | 1212 | .. versionadded:: 3.2 |
Nick Coghlan | 04e2e3f | 2012-06-23 19:52:05 +1000 | [diff] [blame] | 1213 | |
Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 1214 | .. function:: getcoroutinestate(coroutine) |
| 1215 | |
| 1216 | Get current state of a coroutine object. The function is intended to be |
| 1217 | used with coroutine objects created by :keyword:`async def` functions, but |
| 1218 | will accept any coroutine-like object that has ``cr_running`` and |
| 1219 | ``cr_frame`` attributes. |
| 1220 | |
| 1221 | Possible states are: |
| 1222 | * CORO_CREATED: Waiting to start execution. |
| 1223 | * CORO_RUNNING: Currently being executed by the interpreter. |
| 1224 | * CORO_SUSPENDED: Currently suspended at an await expression. |
| 1225 | * CORO_CLOSED: Execution has completed. |
| 1226 | |
| 1227 | .. versionadded:: 3.5 |
| 1228 | |
Nick Coghlan | 04e2e3f | 2012-06-23 19:52:05 +1000 | [diff] [blame] | 1229 | The current internal state of the generator can also be queried. This is |
| 1230 | mostly useful for testing purposes, to ensure that internal state is being |
| 1231 | updated as expected: |
| 1232 | |
| 1233 | .. function:: getgeneratorlocals(generator) |
| 1234 | |
| 1235 | Get the mapping of live local variables in *generator* to their current |
| 1236 | values. A dictionary is returned that maps from variable names to values. |
| 1237 | This is the equivalent of calling :func:`locals` in the body of the |
| 1238 | generator, and all the same caveats apply. |
| 1239 | |
| 1240 | If *generator* is a :term:`generator` with no currently associated frame, |
| 1241 | then an empty dictionary is returned. :exc:`TypeError` is raised if |
| 1242 | *generator* is not a Python generator object. |
| 1243 | |
| 1244 | .. impl-detail:: |
| 1245 | |
| 1246 | This function relies on the generator exposing a Python stack frame |
| 1247 | for introspection, which isn't guaranteed to be the case in all |
| 1248 | implementations of Python. In such cases, this function will always |
| 1249 | return an empty dictionary. |
| 1250 | |
| 1251 | .. versionadded:: 3.3 |
Nick Coghlan | f94a16b | 2013-09-22 22:46:49 +1000 | [diff] [blame] | 1252 | |
Yury Selivanov | 5376ba9 | 2015-06-22 12:19:30 -0400 | [diff] [blame] | 1253 | .. function:: getcoroutinelocals(coroutine) |
| 1254 | |
| 1255 | This function is analogous to :func:`~inspect.getgeneratorlocals`, but |
| 1256 | works for coroutine objects created by :keyword:`async def` functions. |
| 1257 | |
| 1258 | .. versionadded:: 3.5 |
| 1259 | |
Nick Coghlan | f94a16b | 2013-09-22 22:46:49 +1000 | [diff] [blame] | 1260 | |
Yury Selivanov | ea75a51 | 2016-10-20 13:06:30 -0400 | [diff] [blame] | 1261 | .. _inspect-module-co-flags: |
| 1262 | |
| 1263 | Code Objects Bit Flags |
| 1264 | ---------------------- |
| 1265 | |
| 1266 | Python code objects have a ``co_flags`` attribute, which is a bitmap of |
| 1267 | the following flags: |
| 1268 | |
| 1269 | .. data:: CO_NEWLOCALS |
| 1270 | |
| 1271 | If set, a new dict will be created for the frame's ``f_locals`` when |
| 1272 | the code object is executed. |
| 1273 | |
| 1274 | .. data:: CO_VARARGS |
| 1275 | |
| 1276 | The code object has a variable positional parameter (``*args``-like). |
| 1277 | |
| 1278 | .. data:: CO_VARKEYWORDS |
| 1279 | |
| 1280 | The code object has a variable keyword parameter (``**kwargs``-like). |
| 1281 | |
| 1282 | .. data:: CO_GENERATOR |
| 1283 | |
| 1284 | The flag is set when the code object is a generator function, i.e. |
| 1285 | a generator object is returned when the code object is executed. |
| 1286 | |
| 1287 | .. data:: CO_NOFREE |
| 1288 | |
| 1289 | The flag is set if there are no free or cell variables. |
| 1290 | |
| 1291 | .. data:: CO_COROUTINE |
| 1292 | |
Yury Selivanov | b738a1f | 2016-10-20 16:30:51 -0400 | [diff] [blame] | 1293 | The flag is set when the code object is a coroutine function. |
| 1294 | When the code object is executed it returns a coroutine object. |
| 1295 | See :pep:`492` for more details. |
Yury Selivanov | ea75a51 | 2016-10-20 13:06:30 -0400 | [diff] [blame] | 1296 | |
| 1297 | .. versionadded:: 3.5 |
| 1298 | |
| 1299 | .. data:: CO_ITERABLE_COROUTINE |
| 1300 | |
Yury Selivanov | b738a1f | 2016-10-20 16:30:51 -0400 | [diff] [blame] | 1301 | The flag is used to transform generators into generator-based |
| 1302 | coroutines. Generator objects with this flag can be used in |
| 1303 | ``await`` expression, and can ``yield from`` coroutine objects. |
| 1304 | See :pep:`492` for more details. |
Yury Selivanov | ea75a51 | 2016-10-20 13:06:30 -0400 | [diff] [blame] | 1305 | |
| 1306 | .. versionadded:: 3.5 |
| 1307 | |
Yury Selivanov | e20fed9 | 2016-10-20 13:11:34 -0400 | [diff] [blame] | 1308 | .. data:: CO_ASYNC_GENERATOR |
| 1309 | |
Yury Selivanov | b738a1f | 2016-10-20 16:30:51 -0400 | [diff] [blame] | 1310 | The flag is set when the code object is an asynchronous generator |
| 1311 | function. When the code object is executed it returns an |
| 1312 | asynchronous generator object. See :pep:`525` for more details. |
Yury Selivanov | e20fed9 | 2016-10-20 13:11:34 -0400 | [diff] [blame] | 1313 | |
| 1314 | .. versionadded:: 3.6 |
| 1315 | |
Yury Selivanov | ea75a51 | 2016-10-20 13:06:30 -0400 | [diff] [blame] | 1316 | .. note:: |
| 1317 | The flags are specific to CPython, and may not be defined in other |
| 1318 | Python implementations. Furthermore, the flags are an implementation |
| 1319 | detail, and can be removed or deprecated in future Python releases. |
| 1320 | It's recommended to use public APIs from the :mod:`inspect` module |
| 1321 | for any introspection needs. |
| 1322 | |
| 1323 | |
Nick Coghlan | 367df12 | 2013-10-27 01:57:34 +1000 | [diff] [blame] | 1324 | .. _inspect-module-cli: |
| 1325 | |
Nick Coghlan | f94a16b | 2013-09-22 22:46:49 +1000 | [diff] [blame] | 1326 | Command Line Interface |
| 1327 | ---------------------- |
| 1328 | |
| 1329 | The :mod:`inspect` module also provides a basic introspection capability |
| 1330 | from the command line. |
| 1331 | |
| 1332 | .. program:: inspect |
| 1333 | |
| 1334 | By default, accepts the name of a module and prints the source of that |
| 1335 | module. A class or function within the module can be printed instead by |
| 1336 | appended a colon and the qualified name of the target object. |
| 1337 | |
| 1338 | .. cmdoption:: --details |
| 1339 | |
| 1340 | Print information about the specified object rather than the source code |