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