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