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