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