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 | |
| 193 | |
| 194 | .. function:: getmodulename(path) |
| 195 | |
| 196 | Return the name of the module named by the file *path*, without including the |
| 197 | names of enclosing packages. This uses the same algorithm as the interpreter |
| 198 | uses when searching for modules. If the name cannot be matched according to the |
| 199 | interpreter's rules, ``None`` is returned. |
| 200 | |
| 201 | |
| 202 | .. function:: ismodule(object) |
| 203 | |
| 204 | Return true if the object is a module. |
| 205 | |
| 206 | |
| 207 | .. function:: isclass(object) |
| 208 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 209 | Return true if the object is a class, whether built-in or created in Python |
| 210 | code. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 211 | |
| 212 | |
| 213 | .. function:: ismethod(object) |
| 214 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 215 | Return true if the object is a bound method written in Python. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 216 | |
| 217 | |
| 218 | .. function:: isfunction(object) |
| 219 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 220 | Return true if the object is a Python function, which includes functions |
| 221 | created by a :term:`lambda` expression. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 222 | |
| 223 | |
Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 224 | .. function:: isgeneratorfunction(object) |
| 225 | |
| 226 | Return true if the object is a Python generator function. |
| 227 | |
| 228 | |
| 229 | .. function:: isgenerator(object) |
| 230 | |
| 231 | Return true if the object is a generator. |
| 232 | |
| 233 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 234 | .. function:: istraceback(object) |
| 235 | |
| 236 | Return true if the object is a traceback. |
| 237 | |
| 238 | |
| 239 | .. function:: isframe(object) |
| 240 | |
| 241 | Return true if the object is a frame. |
| 242 | |
| 243 | |
| 244 | .. function:: iscode(object) |
| 245 | |
| 246 | Return true if the object is a code. |
| 247 | |
| 248 | |
| 249 | .. function:: isbuiltin(object) |
| 250 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 251 | 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] | 252 | |
| 253 | |
| 254 | .. function:: isroutine(object) |
| 255 | |
| 256 | Return true if the object is a user-defined or built-in function or method. |
| 257 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 258 | |
Christian Heimes | be5b30b | 2008-03-03 19:18:51 +0000 | [diff] [blame] | 259 | .. function:: isabstract(object) |
| 260 | |
| 261 | Return true if the object is an abstract base class. |
| 262 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 263 | |
| 264 | .. function:: ismethoddescriptor(object) |
| 265 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 266 | Return true if the object is a method descriptor, but not if |
| 267 | :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin` |
| 268 | are true. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 269 | |
Georg Brandl | e6bcc91 | 2008-05-12 18:05:20 +0000 | [diff] [blame] | 270 | This, for example, is true of ``int.__add__``. An object passing this test |
| 271 | has a :attr:`__get__` attribute but not a :attr:`__set__` attribute, but |
| 272 | beyond that the set of attributes varies. :attr:`__name__` is usually |
| 273 | sensible, and :attr:`__doc__` often is. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 274 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 275 | Methods implemented via descriptors that also pass one of the other tests |
| 276 | return false from the :func:`ismethoddescriptor` test, simply because the |
| 277 | other tests promise more -- you can, e.g., count on having the |
Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 278 | :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 279 | |
| 280 | |
| 281 | .. function:: isdatadescriptor(object) |
| 282 | |
| 283 | Return true if the object is a data descriptor. |
| 284 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 285 | Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute. |
| 286 | Examples are properties (defined in Python), getsets, and members. The |
| 287 | latter two are defined in C and there are more specific tests available for |
| 288 | those types, which is robust across Python implementations. Typically, data |
| 289 | descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes |
| 290 | (properties, getsets, and members have both of these attributes), but this is |
| 291 | not guaranteed. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 292 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 293 | |
| 294 | .. function:: isgetsetdescriptor(object) |
| 295 | |
| 296 | Return true if the object is a getset descriptor. |
| 297 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 298 | .. impl-detail:: |
| 299 | |
| 300 | getsets are attributes defined in extension modules via |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 301 | :c:type:`PyGetSetDef` structures. For Python implementations without such |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 302 | types, this method will always return ``False``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 303 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 304 | |
| 305 | .. function:: ismemberdescriptor(object) |
| 306 | |
| 307 | Return true if the object is a member descriptor. |
| 308 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 309 | .. impl-detail:: |
| 310 | |
| 311 | Member descriptors are attributes defined in extension modules via |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 312 | :c:type:`PyMemberDef` structures. For Python implementations without such |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 313 | types, this method will always return ``False``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 314 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 315 | |
| 316 | .. _inspect-source: |
| 317 | |
| 318 | Retrieving source code |
| 319 | ---------------------- |
| 320 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 321 | .. function:: getdoc(object) |
| 322 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 323 | Get the documentation string for an object, cleaned up with :func:`cleandoc`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 324 | |
| 325 | |
| 326 | .. function:: getcomments(object) |
| 327 | |
| 328 | Return in a single string any lines of comments immediately preceding the |
| 329 | object's source code (for a class, function, or method), or at the top of the |
| 330 | Python source file (if the object is a module). |
| 331 | |
| 332 | |
| 333 | .. function:: getfile(object) |
| 334 | |
| 335 | Return the name of the (text or binary) file in which an object was defined. |
| 336 | This will fail with a :exc:`TypeError` if the object is a built-in module, |
| 337 | class, or function. |
| 338 | |
| 339 | |
| 340 | .. function:: getmodule(object) |
| 341 | |
| 342 | Try to guess which module an object was defined in. |
| 343 | |
| 344 | |
| 345 | .. function:: getsourcefile(object) |
| 346 | |
| 347 | Return the name of the Python source file in which an object was defined. This |
| 348 | will fail with a :exc:`TypeError` if the object is a built-in module, class, or |
| 349 | function. |
| 350 | |
| 351 | |
| 352 | .. function:: getsourcelines(object) |
| 353 | |
| 354 | Return a list of source lines and starting line number for an object. The |
| 355 | argument may be a module, class, method, function, traceback, frame, or code |
| 356 | object. The source code is returned as a list of the lines corresponding to the |
| 357 | 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^] | 358 | 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] | 359 | be retrieved. |
| 360 | |
Antoine Pitrou | 62ab10a0 | 2011-10-12 20:10:51 +0200 | [diff] [blame^] | 361 | .. versionchanged:: 3.3 |
| 362 | :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the |
| 363 | former. |
| 364 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 365 | |
| 366 | .. function:: getsource(object) |
| 367 | |
| 368 | Return the text of the source code for an object. The argument may be a module, |
| 369 | class, method, function, traceback, frame, or code object. The source code is |
Antoine Pitrou | 62ab10a0 | 2011-10-12 20:10:51 +0200 | [diff] [blame^] | 370 | 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] | 371 | cannot be retrieved. |
| 372 | |
Antoine Pitrou | 62ab10a0 | 2011-10-12 20:10:51 +0200 | [diff] [blame^] | 373 | .. versionchanged:: 3.3 |
| 374 | :exc:`OSError` is raised instead of :exc:`IOError`, now an alias of the |
| 375 | former. |
| 376 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 377 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 378 | .. function:: cleandoc(doc) |
| 379 | |
| 380 | Clean up indentation from docstrings that are indented to line up with blocks |
| 381 | of code. Any whitespace that can be uniformly removed from the second line |
| 382 | onwards is removed. Also, all tabs are expanded to spaces. |
| 383 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 384 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 385 | .. _inspect-classes-functions: |
| 386 | |
| 387 | Classes and functions |
| 388 | --------------------- |
| 389 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 390 | .. function:: getclasstree(classes, unique=False) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 391 | |
| 392 | Arrange the given list of classes into a hierarchy of nested lists. Where a |
| 393 | nested list appears, it contains classes derived from the class whose entry |
| 394 | immediately precedes the list. Each entry is a 2-tuple containing a class and a |
| 395 | tuple of its base classes. If the *unique* argument is true, exactly one entry |
| 396 | appears in the returned structure for each class in the given list. Otherwise, |
| 397 | classes using multiple inheritance and their descendants will appear multiple |
| 398 | times. |
| 399 | |
| 400 | |
| 401 | .. function:: getargspec(func) |
| 402 | |
Georg Brandl | 8240275 | 2010-01-09 09:48:46 +0000 | [diff] [blame] | 403 | 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] | 404 | :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is |
| 405 | returned. *args* is a list of the argument names. *varargs* and *keywords* |
| 406 | are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a |
| 407 | tuple of default argument values or None if there are no default arguments; |
| 408 | if this tuple has *n* elements, they correspond to the last *n* elements |
| 409 | listed in *args*. |
Georg Brandl | 138bcb5 | 2007-09-12 19:04:21 +0000 | [diff] [blame] | 410 | |
| 411 | .. deprecated:: 3.0 |
| 412 | Use :func:`getfullargspec` instead, which provides information about |
Benjamin Peterson | 3e8e9cc | 2008-11-12 21:26:46 +0000 | [diff] [blame] | 413 | keyword-only arguments and annotations. |
Georg Brandl | 138bcb5 | 2007-09-12 19:04:21 +0000 | [diff] [blame] | 414 | |
| 415 | |
| 416 | .. function:: getfullargspec(func) |
| 417 | |
Georg Brandl | 8240275 | 2010-01-09 09:48:46 +0000 | [diff] [blame] | 418 | Get the names and default values of a Python function's arguments. A |
| 419 | :term:`named tuple` is returned: |
Georg Brandl | 138bcb5 | 2007-09-12 19:04:21 +0000 | [diff] [blame] | 420 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 421 | ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, |
| 422 | annotations)`` |
Georg Brandl | 138bcb5 | 2007-09-12 19:04:21 +0000 | [diff] [blame] | 423 | |
| 424 | *args* is a list of the argument names. *varargs* and *varkw* are the names |
| 425 | of the ``*`` and ``**`` arguments or ``None``. *defaults* is an n-tuple of |
| 426 | the default values of the last n arguments. *kwonlyargs* is a list of |
| 427 | keyword-only argument names. *kwonlydefaults* is a dictionary mapping names |
| 428 | from kwonlyargs to defaults. *annotations* is a dictionary mapping argument |
| 429 | names to annotations. |
| 430 | |
| 431 | The first four items in the tuple correspond to :func:`getargspec`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 432 | |
| 433 | |
| 434 | .. function:: getargvalues(frame) |
| 435 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 436 | Get information about arguments passed into a particular frame. A |
| 437 | :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is |
Georg Brandl | b30f330 | 2011-01-06 09:23:56 +0000 | [diff] [blame] | 438 | returned. *args* is a list of the argument names. *varargs* and *keywords* |
| 439 | are the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 440 | locals dictionary of the given frame. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 441 | |
| 442 | |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 443 | .. function:: formatargspec(args[, varargs, varkw, defaults, formatarg, formatvarargs, formatvarkw, formatvalue]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 444 | |
| 445 | Format a pretty argument spec from the four values returned by |
| 446 | :func:`getargspec`. The format\* arguments are the corresponding optional |
| 447 | formatting functions that are called to turn names and values into strings. |
| 448 | |
| 449 | |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 450 | .. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 451 | |
| 452 | Format a pretty argument spec from the four values returned by |
| 453 | :func:`getargvalues`. The format\* arguments are the corresponding optional |
| 454 | formatting functions that are called to turn names and values into strings. |
| 455 | |
| 456 | |
| 457 | .. function:: getmro(cls) |
| 458 | |
| 459 | Return a tuple of class cls's base classes, including cls, in method resolution |
| 460 | order. No class appears more than once in this tuple. Note that the method |
| 461 | resolution order depends on cls's type. Unless a very peculiar user-defined |
| 462 | metatype is in use, cls will be the first element of the tuple. |
| 463 | |
| 464 | |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 465 | .. function:: getcallargs(func[, *args][, **kwds]) |
| 466 | |
| 467 | Bind the *args* and *kwds* to the argument names of the Python function or |
| 468 | method *func*, as if it was called with them. For bound methods, bind also the |
| 469 | first argument (typically named ``self``) to the associated instance. A dict |
| 470 | is returned, mapping the argument names (including the names of the ``*`` and |
| 471 | ``**`` arguments, if any) to their values from *args* and *kwds*. In case of |
| 472 | invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise |
| 473 | an exception because of incompatible signature, an exception of the same type |
| 474 | and the same or similar message is raised. For example:: |
| 475 | |
| 476 | >>> from inspect import getcallargs |
| 477 | >>> def f(a, b=1, *pos, **named): |
| 478 | ... pass |
| 479 | >>> getcallargs(f, 1, 2, 3) |
| 480 | {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)} |
| 481 | >>> getcallargs(f, a=2, x=4) |
| 482 | {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()} |
| 483 | >>> getcallargs(f) |
| 484 | Traceback (most recent call last): |
| 485 | ... |
| 486 | TypeError: f() takes at least 1 argument (0 given) |
| 487 | |
| 488 | .. versionadded:: 3.2 |
| 489 | |
| 490 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 491 | .. _inspect-stack: |
| 492 | |
| 493 | The interpreter stack |
| 494 | --------------------- |
| 495 | |
| 496 | When the following functions return "frame records," each record is a tuple of |
| 497 | six items: the frame object, the filename, the line number of the current line, |
| 498 | the function name, a list of lines of context from the source code, and the |
| 499 | index of the current line within that list. |
| 500 | |
Georg Brandl | e720c0a | 2009-04-27 16:20:50 +0000 | [diff] [blame] | 501 | .. note:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 502 | |
| 503 | Keeping references to frame objects, as found in the first element of the frame |
| 504 | records these functions return, can cause your program to create reference |
| 505 | cycles. Once a reference cycle has been created, the lifespan of all objects |
| 506 | which can be accessed from the objects which form the cycle can become much |
| 507 | longer even if Python's optional cycle detector is enabled. If such cycles must |
| 508 | be created, it is important to ensure they are explicitly broken to avoid the |
| 509 | delayed destruction of objects and increased memory consumption which occurs. |
| 510 | |
| 511 | Though the cycle detector will catch these, destruction of the frames (and local |
| 512 | variables) can be made deterministic by removing the cycle in a |
| 513 | :keyword:`finally` clause. This is also important if the cycle detector was |
| 514 | disabled when Python was compiled or using :func:`gc.disable`. For example:: |
| 515 | |
| 516 | def handle_stackframe_without_leak(): |
| 517 | frame = inspect.currentframe() |
| 518 | try: |
| 519 | # do something with the frame |
| 520 | finally: |
| 521 | del frame |
| 522 | |
| 523 | The optional *context* argument supported by most of these functions specifies |
| 524 | the number of lines of context to return, which are centered around the current |
| 525 | line. |
| 526 | |
| 527 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 528 | .. function:: getframeinfo(frame, context=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 529 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 530 | Get information about a frame or traceback object. A :term:`named tuple` |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 531 | ``Traceback(filename, lineno, function, code_context, index)`` is returned. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 532 | |
| 533 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 534 | .. function:: getouterframes(frame, context=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 535 | |
| 536 | Get a list of frame records for a frame and all outer frames. These frames |
| 537 | represent the calls that lead to the creation of *frame*. The first entry in the |
| 538 | returned list represents *frame*; the last entry represents the outermost call |
| 539 | on *frame*'s stack. |
| 540 | |
| 541 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 542 | .. function:: getinnerframes(traceback, context=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 543 | |
| 544 | Get a list of frame records for a traceback's frame and all inner frames. These |
| 545 | frames represent calls made as a consequence of *frame*. The first entry in the |
| 546 | list represents *traceback*; the last entry represents where the exception was |
| 547 | raised. |
| 548 | |
| 549 | |
| 550 | .. function:: currentframe() |
| 551 | |
| 552 | Return the frame object for the caller's stack frame. |
| 553 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 554 | .. impl-detail:: |
| 555 | |
| 556 | This function relies on Python stack frame support in the interpreter, |
| 557 | which isn't guaranteed to exist in all implementations of Python. If |
| 558 | running in an implementation without Python stack frame support this |
| 559 | function returns ``None``. |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 560 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 561 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 562 | .. function:: stack(context=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 563 | |
| 564 | Return a list of frame records for the caller's stack. The first entry in the |
| 565 | returned list represents the caller; the last entry represents the outermost |
| 566 | call on the stack. |
| 567 | |
| 568 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 569 | .. function:: trace(context=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 570 | |
| 571 | Return a list of frame records for the stack between the current frame and the |
| 572 | frame in which an exception currently being handled was raised in. The first |
| 573 | entry in the list represents the caller; the last entry represents where the |
| 574 | exception was raised. |
| 575 | |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 576 | |
| 577 | Fetching attributes statically |
| 578 | ------------------------------ |
| 579 | |
| 580 | Both :func:`getattr` and :func:`hasattr` can trigger code execution when |
| 581 | fetching or checking for the existence of attributes. Descriptors, like |
| 582 | properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__` |
| 583 | may be called. |
| 584 | |
| 585 | For cases where you want passive introspection, like documentation tools, this |
Éric Araujo | 941afed | 2011-09-01 02:47:34 +0200 | [diff] [blame] | 586 | 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] | 587 | but avoids executing code when it fetches attributes. |
| 588 | |
| 589 | .. function:: getattr_static(obj, attr, default=None) |
| 590 | |
| 591 | Retrieve attributes without triggering dynamic lookup via the |
Éric Araujo | 941afed | 2011-09-01 02:47:34 +0200 | [diff] [blame] | 592 | descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`. |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 593 | |
| 594 | Note: this function may not be able to retrieve all attributes |
| 595 | that getattr can fetch (like dynamically created attributes) |
| 596 | and may find attributes that getattr can't (like descriptors |
| 597 | that raise AttributeError). It can also return descriptors objects |
| 598 | instead of instance members. |
| 599 | |
Éric Araujo | 941afed | 2011-09-01 02:47:34 +0200 | [diff] [blame] | 600 | 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] | 601 | property) then this function will be unable to find instance members. |
Nick Coghlan | 2dad5ca | 2010-11-21 03:55:53 +0000 | [diff] [blame] | 602 | |
Michael Foord | dcebe0f | 2011-03-15 19:20:44 -0400 | [diff] [blame] | 603 | .. versionadded:: 3.2 |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 604 | |
Éric Araujo | 941afed | 2011-09-01 02:47:34 +0200 | [diff] [blame] | 605 | :func:`getattr_static` does not resolve descriptors, for example slot descriptors or |
Michael Foord | e516265 | 2010-11-20 16:40:44 +0000 | [diff] [blame] | 606 | getset descriptors on objects implemented in C. The descriptor object |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 607 | is returned instead of the underlying attribute. |
| 608 | |
| 609 | You can handle these with code like the following. Note that |
| 610 | for arbitrary getset descriptors invoking these may trigger |
| 611 | code execution:: |
| 612 | |
| 613 | # example code for resolving the builtin descriptor types |
Éric Araujo | 28053fb | 2010-11-22 03:09:19 +0000 | [diff] [blame] | 614 | class _foo: |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 615 | __slots__ = ['foo'] |
| 616 | |
| 617 | slot_descriptor = type(_foo.foo) |
| 618 | getset_descriptor = type(type(open(__file__)).name) |
| 619 | wrapper_descriptor = type(str.__dict__['__add__']) |
| 620 | descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor) |
| 621 | |
| 622 | result = getattr_static(some_object, 'foo') |
| 623 | if type(result) in descriptor_types: |
| 624 | try: |
| 625 | result = result.__get__() |
| 626 | except AttributeError: |
| 627 | # descriptors can raise AttributeError to |
| 628 | # indicate there is no underlying value |
| 629 | # in which case the descriptor itself will |
| 630 | # have to do |
| 631 | pass |
Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 632 | |
Nick Coghlan | 2dad5ca | 2010-11-21 03:55:53 +0000 | [diff] [blame] | 633 | |
Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 634 | Current State of a Generator |
| 635 | ---------------------------- |
| 636 | |
| 637 | When implementing coroutine schedulers and for other advanced uses of |
| 638 | generators, it is useful to determine whether a generator is currently |
| 639 | executing, is waiting to start or resume or execution, or has already |
Raymond Hettinger | 48f3bd3 | 2010-12-16 00:30:53 +0000 | [diff] [blame] | 640 | terminated. :func:`getgeneratorstate` allows the current state of a |
Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 641 | generator to be determined easily. |
| 642 | |
| 643 | .. function:: getgeneratorstate(generator) |
| 644 | |
Raymond Hettinger | 48f3bd3 | 2010-12-16 00:30:53 +0000 | [diff] [blame] | 645 | Get current state of a generator-iterator. |
Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 646 | |
Raymond Hettinger | 48f3bd3 | 2010-12-16 00:30:53 +0000 | [diff] [blame] | 647 | Possible states are: |
Raymond Hettinger | a275c98 | 2011-01-20 04:03:19 +0000 | [diff] [blame] | 648 | * GEN_CREATED: Waiting to start execution. |
| 649 | * GEN_RUNNING: Currently being executed by the interpreter. |
| 650 | * GEN_SUSPENDED: Currently suspended at a yield expression. |
| 651 | * GEN_CLOSED: Execution has completed. |
Nick Coghlan | e0f0465 | 2010-11-21 03:44:04 +0000 | [diff] [blame] | 652 | |
Nick Coghlan | 2dad5ca | 2010-11-21 03:55:53 +0000 | [diff] [blame] | 653 | .. versionadded:: 3.2 |