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