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 | |
| 9 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 10 | The :mod:`inspect` module provides several useful functions to help get |
| 11 | information about live objects such as modules, classes, methods, functions, |
| 12 | tracebacks, frame objects, and code objects. For example, it can help you |
| 13 | examine the contents of a class, retrieve the source code of a method, extract |
| 14 | and format the argument list for a function, or get all the information you need |
| 15 | to display a detailed traceback. |
| 16 | |
| 17 | There are four main kinds of services provided by this module: type checking, |
| 18 | getting source code, inspecting classes and functions, and examining the |
| 19 | interpreter stack. |
| 20 | |
| 21 | |
| 22 | .. _inspect-types: |
| 23 | |
| 24 | Types and members |
| 25 | ----------------- |
| 26 | |
| 27 | 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] | 28 | 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] | 29 | provided as convenient choices for the second argument to :func:`getmembers`. |
| 30 | They also help you determine when you can expect to find the following special |
| 31 | attributes: |
| 32 | |
Georg Brandl | 55ac8f0 | 2007-09-01 13:51:09 +0000 | [diff] [blame] | 33 | +-----------+-----------------+---------------------------+ |
| 34 | | Type | Attribute | Description | |
| 35 | +===========+=================+===========================+ |
| 36 | | module | __doc__ | documentation string | |
| 37 | +-----------+-----------------+---------------------------+ |
| 38 | | | __file__ | filename (missing for | |
| 39 | | | | built-in modules) | |
| 40 | +-----------+-----------------+---------------------------+ |
| 41 | | class | __doc__ | documentation string | |
| 42 | +-----------+-----------------+---------------------------+ |
| 43 | | | __module__ | name of module in which | |
| 44 | | | | this class was defined | |
| 45 | +-----------+-----------------+---------------------------+ |
| 46 | | method | __doc__ | documentation string | |
| 47 | +-----------+-----------------+---------------------------+ |
| 48 | | | __name__ | name with which this | |
| 49 | | | | method was defined | |
| 50 | +-----------+-----------------+---------------------------+ |
Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 51 | | | __func__ | function object | |
Georg Brandl | 55ac8f0 | 2007-09-01 13:51:09 +0000 | [diff] [blame] | 52 | | | | containing implementation | |
| 53 | | | | of method | |
| 54 | +-----------+-----------------+---------------------------+ |
Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 55 | | | __self__ | instance to which this | |
Georg Brandl | 55ac8f0 | 2007-09-01 13:51:09 +0000 | [diff] [blame] | 56 | | | | method is bound, or | |
| 57 | | | | ``None`` | |
| 58 | +-----------+-----------------+---------------------------+ |
| 59 | | function | __doc__ | documentation string | |
| 60 | +-----------+-----------------+---------------------------+ |
| 61 | | | __name__ | name with which this | |
| 62 | | | | function was defined | |
| 63 | +-----------+-----------------+---------------------------+ |
| 64 | | | __code__ | code object containing | |
| 65 | | | | compiled function | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 66 | | | | :term:`bytecode` | |
Georg Brandl | 55ac8f0 | 2007-09-01 13:51:09 +0000 | [diff] [blame] | 67 | +-----------+-----------------+---------------------------+ |
| 68 | | | __defaults__ | tuple of any default | |
| 69 | | | | values for arguments | |
| 70 | +-----------+-----------------+---------------------------+ |
| 71 | | | __globals__ | global namespace in which | |
| 72 | | | | this function was defined | |
| 73 | +-----------+-----------------+---------------------------+ |
| 74 | | traceback | tb_frame | frame object at this | |
| 75 | | | | level | |
| 76 | +-----------+-----------------+---------------------------+ |
| 77 | | | tb_lasti | index of last attempted | |
| 78 | | | | instruction in bytecode | |
| 79 | +-----------+-----------------+---------------------------+ |
| 80 | | | tb_lineno | current line number in | |
| 81 | | | | Python source code | |
| 82 | +-----------+-----------------+---------------------------+ |
| 83 | | | tb_next | next inner traceback | |
| 84 | | | | object (called by this | |
| 85 | | | | level) | |
| 86 | +-----------+-----------------+---------------------------+ |
| 87 | | frame | f_back | next outer frame object | |
| 88 | | | | (this frame's caller) | |
| 89 | +-----------+-----------------+---------------------------+ |
Georg Brandl | c4a55fc | 2010-02-06 18:46:57 +0000 | [diff] [blame] | 90 | | | f_builtins | builtins namespace seen | |
Georg Brandl | 55ac8f0 | 2007-09-01 13:51:09 +0000 | [diff] [blame] | 91 | | | | by this frame | |
| 92 | +-----------+-----------------+---------------------------+ |
| 93 | | | f_code | code object being | |
| 94 | | | | executed in this frame | |
| 95 | +-----------+-----------------+---------------------------+ |
Georg Brandl | 55ac8f0 | 2007-09-01 13:51:09 +0000 | [diff] [blame] | 96 | | | f_globals | global namespace seen by | |
| 97 | | | | this frame | |
| 98 | +-----------+-----------------+---------------------------+ |
| 99 | | | f_lasti | index of last attempted | |
| 100 | | | | instruction in bytecode | |
| 101 | +-----------+-----------------+---------------------------+ |
| 102 | | | f_lineno | current line number in | |
| 103 | | | | Python source code | |
| 104 | +-----------+-----------------+---------------------------+ |
| 105 | | | f_locals | local namespace seen by | |
| 106 | | | | this frame | |
| 107 | +-----------+-----------------+---------------------------+ |
| 108 | | | f_restricted | 0 or 1 if frame is in | |
| 109 | | | | restricted execution mode | |
| 110 | +-----------+-----------------+---------------------------+ |
| 111 | | | f_trace | tracing function for this | |
| 112 | | | | frame, or ``None`` | |
| 113 | +-----------+-----------------+---------------------------+ |
| 114 | | code | co_argcount | number of arguments (not | |
| 115 | | | | including \* or \*\* | |
| 116 | | | | args) | |
| 117 | +-----------+-----------------+---------------------------+ |
| 118 | | | co_code | string of raw compiled | |
| 119 | | | | bytecode | |
| 120 | +-----------+-----------------+---------------------------+ |
| 121 | | | co_consts | tuple of constants used | |
| 122 | | | | in the bytecode | |
| 123 | +-----------+-----------------+---------------------------+ |
| 124 | | | co_filename | name of file in which | |
| 125 | | | | this code object was | |
| 126 | | | | created | |
| 127 | +-----------+-----------------+---------------------------+ |
| 128 | | | co_firstlineno | number of first line in | |
| 129 | | | | Python source code | |
| 130 | +-----------+-----------------+---------------------------+ |
| 131 | | | co_flags | bitmap: 1=optimized ``|`` | |
| 132 | | | | 2=newlocals ``|`` 4=\*arg | |
| 133 | | | | ``|`` 8=\*\*arg | |
| 134 | +-----------+-----------------+---------------------------+ |
| 135 | | | co_lnotab | encoded mapping of line | |
| 136 | | | | numbers to bytecode | |
| 137 | | | | indices | |
| 138 | +-----------+-----------------+---------------------------+ |
| 139 | | | co_name | name with which this code | |
| 140 | | | | object was defined | |
| 141 | +-----------+-----------------+---------------------------+ |
| 142 | | | co_names | tuple of names of local | |
| 143 | | | | variables | |
| 144 | +-----------+-----------------+---------------------------+ |
| 145 | | | co_nlocals | number of local variables | |
| 146 | +-----------+-----------------+---------------------------+ |
| 147 | | | co_stacksize | virtual machine stack | |
| 148 | | | | space required | |
| 149 | +-----------+-----------------+---------------------------+ |
| 150 | | | co_varnames | tuple of names of | |
| 151 | | | | arguments and local | |
| 152 | | | | variables | |
| 153 | +-----------+-----------------+---------------------------+ |
| 154 | | builtin | __doc__ | documentation string | |
| 155 | +-----------+-----------------+---------------------------+ |
| 156 | | | __name__ | original name of this | |
| 157 | | | | function or method | |
| 158 | +-----------+-----------------+---------------------------+ |
| 159 | | | __self__ | instance to which a | |
| 160 | | | | method is bound, or | |
| 161 | | | | ``None`` | |
| 162 | +-----------+-----------------+---------------------------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 163 | |
| 164 | |
| 165 | .. function:: getmembers(object[, predicate]) |
| 166 | |
| 167 | Return all the members of an object in a list of (name, value) pairs sorted by |
| 168 | name. If the optional *predicate* argument is supplied, only members for which |
| 169 | the predicate returns a true value are included. |
| 170 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 171 | .. note:: |
| 172 | |
| 173 | :func:`getmembers` does not return metaclass attributes when the argument |
| 174 | is a class (this behavior is inherited from the :func:`dir` function). |
| 175 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 176 | |
| 177 | .. function:: getmoduleinfo(path) |
| 178 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 179 | Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode, |
| 180 | module_type)`` of values that describe how Python will interpret the file |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 181 | identified by *path* if it is a module, or ``None`` if it would not be |
| 182 | identified as a module. The return tuple is ``(name, suffix, mode, mtype)``, |
| 183 | where *name* is the name of the module without the name of any enclosing |
| 184 | package, *suffix* is the trailing part of the file name (which may not be a |
| 185 | dot-delimited extension), *mode* is the :func:`open` mode that would be used |
| 186 | (``'r'`` or ``'rb'``), and *mtype* is an integer giving the type of the |
| 187 | module. *mtype* will have a value which can be compared to the constants |
| 188 | defined in the :mod:`imp` module; see the documentation for that module for |
| 189 | more information on module types. |
| 190 | |
| 191 | |
| 192 | .. function:: getmodulename(path) |
| 193 | |
| 194 | Return the name of the module named by the file *path*, without including the |
| 195 | names of enclosing packages. This uses the same algorithm as the interpreter |
| 196 | uses when searching for modules. If the name cannot be matched according to the |
| 197 | interpreter's rules, ``None`` is returned. |
| 198 | |
| 199 | |
| 200 | .. function:: ismodule(object) |
| 201 | |
| 202 | Return true if the object is a module. |
| 203 | |
| 204 | |
| 205 | .. function:: isclass(object) |
| 206 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 207 | Return true if the object is a class, whether built-in or created in Python |
| 208 | code. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 209 | |
| 210 | |
| 211 | .. function:: ismethod(object) |
| 212 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 213 | Return true if the object is a bound method written in Python. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 214 | |
| 215 | |
| 216 | .. function:: isfunction(object) |
| 217 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 218 | Return true if the object is a Python function, which includes functions |
| 219 | created by a :term:`lambda` expression. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 220 | |
| 221 | |
Christian Heimes | 7131fd9 | 2008-02-19 14:21:46 +0000 | [diff] [blame] | 222 | .. function:: isgeneratorfunction(object) |
| 223 | |
| 224 | Return true if the object is a Python generator function. |
| 225 | |
| 226 | |
| 227 | .. function:: isgenerator(object) |
| 228 | |
| 229 | Return true if the object is a generator. |
| 230 | |
| 231 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 232 | .. function:: istraceback(object) |
| 233 | |
| 234 | Return true if the object is a traceback. |
| 235 | |
| 236 | |
| 237 | .. function:: isframe(object) |
| 238 | |
| 239 | Return true if the object is a frame. |
| 240 | |
| 241 | |
| 242 | .. function:: iscode(object) |
| 243 | |
| 244 | Return true if the object is a code. |
| 245 | |
| 246 | |
| 247 | .. function:: isbuiltin(object) |
| 248 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 249 | 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] | 250 | |
| 251 | |
| 252 | .. function:: isroutine(object) |
| 253 | |
| 254 | Return true if the object is a user-defined or built-in function or method. |
| 255 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 256 | |
Christian Heimes | be5b30b | 2008-03-03 19:18:51 +0000 | [diff] [blame] | 257 | .. function:: isabstract(object) |
| 258 | |
| 259 | Return true if the object is an abstract base class. |
| 260 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 261 | |
| 262 | .. function:: ismethoddescriptor(object) |
| 263 | |
Georg Brandl | 39cadc3 | 2010-10-15 16:53:24 +0000 | [diff] [blame] | 264 | Return true if the object is a method descriptor, but not if |
| 265 | :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin` |
| 266 | are true. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 267 | |
Georg Brandl | e6bcc91 | 2008-05-12 18:05:20 +0000 | [diff] [blame] | 268 | This, for example, is true of ``int.__add__``. An object passing this test |
| 269 | has a :attr:`__get__` attribute but not a :attr:`__set__` attribute, but |
| 270 | beyond that the set of attributes varies. :attr:`__name__` is usually |
| 271 | sensible, and :attr:`__doc__` often is. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 272 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 273 | Methods implemented via descriptors that also pass one of the other tests |
| 274 | return false from the :func:`ismethoddescriptor` test, simply because the |
| 275 | other tests promise more -- you can, e.g., count on having the |
Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 276 | :attr:`__func__` attribute (etc) when an object passes :func:`ismethod`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 277 | |
| 278 | |
| 279 | .. function:: isdatadescriptor(object) |
| 280 | |
| 281 | Return true if the object is a data descriptor. |
| 282 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 283 | Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute. |
| 284 | Examples are properties (defined in Python), getsets, and members. The |
| 285 | latter two are defined in C and there are more specific tests available for |
| 286 | those types, which is robust across Python implementations. Typically, data |
| 287 | descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes |
| 288 | (properties, getsets, and members have both of these attributes), but this is |
| 289 | not guaranteed. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 290 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 291 | |
| 292 | .. function:: isgetsetdescriptor(object) |
| 293 | |
| 294 | Return true if the object is a getset descriptor. |
| 295 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 296 | .. impl-detail:: |
| 297 | |
| 298 | getsets are attributes defined in extension modules via |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 299 | :c:type:`PyGetSetDef` structures. For Python implementations without such |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 300 | types, this method will always return ``False``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 301 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 302 | |
| 303 | .. function:: ismemberdescriptor(object) |
| 304 | |
| 305 | Return true if the object is a member descriptor. |
| 306 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 307 | .. impl-detail:: |
| 308 | |
| 309 | Member descriptors are attributes defined in extension modules via |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 310 | :c:type:`PyMemberDef` structures. For Python implementations without such |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 311 | types, this method will always return ``False``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 312 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 313 | |
| 314 | .. _inspect-source: |
| 315 | |
| 316 | Retrieving source code |
| 317 | ---------------------- |
| 318 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 319 | .. function:: getdoc(object) |
| 320 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 321 | Get the documentation string for an object, cleaned up with :func:`cleandoc`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 322 | |
| 323 | |
| 324 | .. function:: getcomments(object) |
| 325 | |
| 326 | Return in a single string any lines of comments immediately preceding the |
| 327 | object's source code (for a class, function, or method), or at the top of the |
| 328 | Python source file (if the object is a module). |
| 329 | |
| 330 | |
| 331 | .. function:: getfile(object) |
| 332 | |
| 333 | Return the name of the (text or binary) file in which an object was defined. |
| 334 | This will fail with a :exc:`TypeError` if the object is a built-in module, |
| 335 | class, or function. |
| 336 | |
| 337 | |
| 338 | .. function:: getmodule(object) |
| 339 | |
| 340 | Try to guess which module an object was defined in. |
| 341 | |
| 342 | |
| 343 | .. function:: getsourcefile(object) |
| 344 | |
| 345 | Return the name of the Python source file in which an object was defined. This |
| 346 | will fail with a :exc:`TypeError` if the object is a built-in module, class, or |
| 347 | function. |
| 348 | |
| 349 | |
| 350 | .. function:: getsourcelines(object) |
| 351 | |
| 352 | Return a list of source lines and starting line number for an object. The |
| 353 | argument may be a module, class, method, function, traceback, frame, or code |
| 354 | object. The source code is returned as a list of the lines corresponding to the |
| 355 | object and the line number indicates where in the original source file the first |
| 356 | line of code was found. An :exc:`IOError` is raised if the source code cannot |
| 357 | be retrieved. |
| 358 | |
| 359 | |
| 360 | .. function:: getsource(object) |
| 361 | |
| 362 | Return the text of the source code for an object. The argument may be a module, |
| 363 | class, method, function, traceback, frame, or code object. The source code is |
| 364 | returned as a single string. An :exc:`IOError` is raised if the source code |
| 365 | cannot be retrieved. |
| 366 | |
| 367 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 368 | .. function:: cleandoc(doc) |
| 369 | |
| 370 | Clean up indentation from docstrings that are indented to line up with blocks |
| 371 | of code. Any whitespace that can be uniformly removed from the second line |
| 372 | onwards is removed. Also, all tabs are expanded to spaces. |
| 373 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 374 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 375 | .. _inspect-classes-functions: |
| 376 | |
| 377 | Classes and functions |
| 378 | --------------------- |
| 379 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 380 | .. function:: getclasstree(classes, unique=False) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 381 | |
| 382 | Arrange the given list of classes into a hierarchy of nested lists. Where a |
| 383 | nested list appears, it contains classes derived from the class whose entry |
| 384 | immediately precedes the list. Each entry is a 2-tuple containing a class and a |
| 385 | tuple of its base classes. If the *unique* argument is true, exactly one entry |
| 386 | appears in the returned structure for each class in the given list. Otherwise, |
| 387 | classes using multiple inheritance and their descendants will appear multiple |
| 388 | times. |
| 389 | |
| 390 | |
| 391 | .. function:: getargspec(func) |
| 392 | |
Georg Brandl | 8240275 | 2010-01-09 09:48:46 +0000 | [diff] [blame] | 393 | Get the names and default values of a Python function's arguments. A |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 394 | :term:`named tuple` ``ArgSpec(args, varargs, keywords, |
| 395 | defaults)`` is returned. *args* is a list of |
Georg Brandl | 138bcb5 | 2007-09-12 19:04:21 +0000 | [diff] [blame] | 396 | the argument names. *varargs* and *varkw* are the names of the ``*`` and |
| 397 | ``**`` arguments or ``None``. *defaults* is a tuple of default argument |
| 398 | values or None if there are no default arguments; if this tuple has *n* |
| 399 | elements, they correspond to the last *n* elements listed in *args*. |
| 400 | |
| 401 | .. deprecated:: 3.0 |
| 402 | Use :func:`getfullargspec` instead, which provides information about |
Benjamin Peterson | 3e8e9cc | 2008-11-12 21:26:46 +0000 | [diff] [blame] | 403 | keyword-only arguments and annotations. |
Georg Brandl | 138bcb5 | 2007-09-12 19:04:21 +0000 | [diff] [blame] | 404 | |
| 405 | |
| 406 | .. function:: getfullargspec(func) |
| 407 | |
Georg Brandl | 8240275 | 2010-01-09 09:48:46 +0000 | [diff] [blame] | 408 | Get the names and default values of a Python function's arguments. A |
| 409 | :term:`named tuple` is returned: |
Georg Brandl | 138bcb5 | 2007-09-12 19:04:21 +0000 | [diff] [blame] | 410 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 411 | ``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, |
| 412 | annotations)`` |
Georg Brandl | 138bcb5 | 2007-09-12 19:04:21 +0000 | [diff] [blame] | 413 | |
| 414 | *args* is a list of the argument names. *varargs* and *varkw* are the names |
| 415 | of the ``*`` and ``**`` arguments or ``None``. *defaults* is an n-tuple of |
| 416 | the default values of the last n arguments. *kwonlyargs* is a list of |
| 417 | keyword-only argument names. *kwonlydefaults* is a dictionary mapping names |
| 418 | from kwonlyargs to defaults. *annotations* is a dictionary mapping argument |
| 419 | names to annotations. |
| 420 | |
| 421 | The first four items in the tuple correspond to :func:`getargspec`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 422 | |
| 423 | |
| 424 | .. function:: getargvalues(frame) |
| 425 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 426 | Get information about arguments passed into a particular frame. A |
| 427 | :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 428 | returned. *args* is a list of the argument names. *varargs* and *varkw* are |
| 429 | the names of the ``*`` and ``**`` arguments or ``None``. *locals* is the |
| 430 | locals dictionary of the given frame. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 431 | |
| 432 | |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 433 | .. function:: formatargspec(args[, varargs, varkw, defaults, formatarg, formatvarargs, formatvarkw, formatvalue]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 434 | |
| 435 | Format a pretty argument spec from the four values returned by |
| 436 | :func:`getargspec`. The format\* arguments are the corresponding optional |
| 437 | formatting functions that are called to turn names and values into strings. |
| 438 | |
| 439 | |
Georg Brandl | c1c4bf8 | 2010-10-15 16:07:41 +0000 | [diff] [blame] | 440 | .. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 441 | |
| 442 | Format a pretty argument spec from the four values returned by |
| 443 | :func:`getargvalues`. The format\* arguments are the corresponding optional |
| 444 | formatting functions that are called to turn names and values into strings. |
| 445 | |
| 446 | |
| 447 | .. function:: getmro(cls) |
| 448 | |
| 449 | Return a tuple of class cls's base classes, including cls, in method resolution |
| 450 | order. No class appears more than once in this tuple. Note that the method |
| 451 | resolution order depends on cls's type. Unless a very peculiar user-defined |
| 452 | metatype is in use, cls will be the first element of the tuple. |
| 453 | |
| 454 | |
Benjamin Peterson | 25cd7eb | 2010-03-30 18:42:32 +0000 | [diff] [blame] | 455 | .. function:: getcallargs(func[, *args][, **kwds]) |
| 456 | |
| 457 | Bind the *args* and *kwds* to the argument names of the Python function or |
| 458 | method *func*, as if it was called with them. For bound methods, bind also the |
| 459 | first argument (typically named ``self``) to the associated instance. A dict |
| 460 | is returned, mapping the argument names (including the names of the ``*`` and |
| 461 | ``**`` arguments, if any) to their values from *args* and *kwds*. In case of |
| 462 | invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise |
| 463 | an exception because of incompatible signature, an exception of the same type |
| 464 | and the same or similar message is raised. For example:: |
| 465 | |
| 466 | >>> from inspect import getcallargs |
| 467 | >>> def f(a, b=1, *pos, **named): |
| 468 | ... pass |
| 469 | >>> getcallargs(f, 1, 2, 3) |
| 470 | {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)} |
| 471 | >>> getcallargs(f, a=2, x=4) |
| 472 | {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()} |
| 473 | >>> getcallargs(f) |
| 474 | Traceback (most recent call last): |
| 475 | ... |
| 476 | TypeError: f() takes at least 1 argument (0 given) |
| 477 | |
| 478 | .. versionadded:: 3.2 |
| 479 | |
| 480 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 481 | .. _inspect-stack: |
| 482 | |
| 483 | The interpreter stack |
| 484 | --------------------- |
| 485 | |
| 486 | When the following functions return "frame records," each record is a tuple of |
| 487 | six items: the frame object, the filename, the line number of the current line, |
| 488 | the function name, a list of lines of context from the source code, and the |
| 489 | index of the current line within that list. |
| 490 | |
Georg Brandl | e720c0a | 2009-04-27 16:20:50 +0000 | [diff] [blame] | 491 | .. note:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 492 | |
| 493 | Keeping references to frame objects, as found in the first element of the frame |
| 494 | records these functions return, can cause your program to create reference |
| 495 | cycles. Once a reference cycle has been created, the lifespan of all objects |
| 496 | which can be accessed from the objects which form the cycle can become much |
| 497 | longer even if Python's optional cycle detector is enabled. If such cycles must |
| 498 | be created, it is important to ensure they are explicitly broken to avoid the |
| 499 | delayed destruction of objects and increased memory consumption which occurs. |
| 500 | |
| 501 | Though the cycle detector will catch these, destruction of the frames (and local |
| 502 | variables) can be made deterministic by removing the cycle in a |
| 503 | :keyword:`finally` clause. This is also important if the cycle detector was |
| 504 | disabled when Python was compiled or using :func:`gc.disable`. For example:: |
| 505 | |
| 506 | def handle_stackframe_without_leak(): |
| 507 | frame = inspect.currentframe() |
| 508 | try: |
| 509 | # do something with the frame |
| 510 | finally: |
| 511 | del frame |
| 512 | |
| 513 | The optional *context* argument supported by most of these functions specifies |
| 514 | the number of lines of context to return, which are centered around the current |
| 515 | line. |
| 516 | |
| 517 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 518 | .. function:: getframeinfo(frame, context=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 519 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 520 | Get information about a frame or traceback object. A :term:`named tuple` |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 521 | ``Traceback(filename, lineno, function, code_context, index)`` is returned. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 522 | |
| 523 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 524 | .. function:: getouterframes(frame, context=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 525 | |
| 526 | Get a list of frame records for a frame and all outer frames. These frames |
| 527 | represent the calls that lead to the creation of *frame*. The first entry in the |
| 528 | returned list represents *frame*; the last entry represents the outermost call |
| 529 | on *frame*'s stack. |
| 530 | |
| 531 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 532 | .. function:: getinnerframes(traceback, context=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 533 | |
| 534 | Get a list of frame records for a traceback's frame and all inner frames. These |
| 535 | frames represent calls made as a consequence of *frame*. The first entry in the |
| 536 | list represents *traceback*; the last entry represents where the exception was |
| 537 | raised. |
| 538 | |
| 539 | |
| 540 | .. function:: currentframe() |
| 541 | |
| 542 | Return the frame object for the caller's stack frame. |
| 543 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 544 | .. impl-detail:: |
| 545 | |
| 546 | This function relies on Python stack frame support in the interpreter, |
| 547 | which isn't guaranteed to exist in all implementations of Python. If |
| 548 | running in an implementation without Python stack frame support this |
| 549 | function returns ``None``. |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 550 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 551 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 552 | .. function:: stack(context=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 553 | |
| 554 | Return a list of frame records for the caller's stack. The first entry in the |
| 555 | returned list represents the caller; the last entry represents the outermost |
| 556 | call on the stack. |
| 557 | |
| 558 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 559 | .. function:: trace(context=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 560 | |
| 561 | Return a list of frame records for the stack between the current frame and the |
| 562 | frame in which an exception currently being handled was raised in. The first |
| 563 | entry in the list represents the caller; the last entry represents where the |
| 564 | exception was raised. |
| 565 | |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 566 | |
| 567 | Fetching attributes statically |
| 568 | ------------------------------ |
| 569 | |
| 570 | Both :func:`getattr` and :func:`hasattr` can trigger code execution when |
| 571 | fetching or checking for the existence of attributes. Descriptors, like |
| 572 | properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__` |
| 573 | may be called. |
| 574 | |
| 575 | For cases where you want passive introspection, like documentation tools, this |
| 576 | can be inconvenient. `getattr_static` has the same signature as :func:`getattr` |
| 577 | but avoids executing code when it fetches attributes. |
| 578 | |
| 579 | .. function:: getattr_static(obj, attr, default=None) |
| 580 | |
| 581 | Retrieve attributes without triggering dynamic lookup via the |
| 582 | descriptor protocol, `__getattr__` or `__getattribute__`. |
| 583 | |
| 584 | Note: this function may not be able to retrieve all attributes |
| 585 | that getattr can fetch (like dynamically created attributes) |
| 586 | and may find attributes that getattr can't (like descriptors |
| 587 | that raise AttributeError). It can also return descriptors objects |
| 588 | instead of instance members. |
| 589 | |
| 590 | There are several cases that will break `getattr_static` or be handled |
| 591 | incorrectly. These are pathological enough not to worry about (i.e. if you do |
| 592 | any of these then you deserve to have everything break anyway): |
| 593 | |
| 594 | * :data:`~object.__dict__` existing (e.g. as a property) but returning the |
| 595 | wrong dictionary or even returning something other than a |
| 596 | dictionary |
| 597 | * classes created with :data:`~object.__slots__` that have the `__slots__` |
| 598 | member deleted from the class, or a fake `__slots__` attribute |
| 599 | attached to the instance, or any other monkeying with |
| 600 | `__slots__` |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 601 | * type objects that lie about their :term:`MRO` |
| 602 | |
Michael Foord | cc7ebb8 | 2010-11-20 16:20:16 +0000 | [diff] [blame^] | 603 | .. note:: |
| 604 | |
| 605 | Classes that override :data:`~object.__mro__` as a property will have this |
| 606 | code executed by `getattr_static`. |
| 607 | |
Michael Foord | 95fc51d | 2010-11-20 15:07:30 +0000 | [diff] [blame] | 608 | Descriptors are not resolved (for example slot descriptors or |
| 609 | getset descriptors on objects implemented in C). The descriptor |
| 610 | is returned instead of the underlying attribute. |
| 611 | |
| 612 | You can handle these with code like the following. Note that |
| 613 | for arbitrary getset descriptors invoking these may trigger |
| 614 | code execution:: |
| 615 | |
| 616 | # example code for resolving the builtin descriptor types |
| 617 | class _foo(object): |
| 618 | __slots__ = ['foo'] |
| 619 | |
| 620 | slot_descriptor = type(_foo.foo) |
| 621 | getset_descriptor = type(type(open(__file__)).name) |
| 622 | wrapper_descriptor = type(str.__dict__['__add__']) |
| 623 | descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor) |
| 624 | |
| 625 | result = getattr_static(some_object, 'foo') |
| 626 | if type(result) in descriptor_types: |
| 627 | try: |
| 628 | result = result.__get__() |
| 629 | except AttributeError: |
| 630 | # descriptors can raise AttributeError to |
| 631 | # indicate there is no underlying value |
| 632 | # in which case the descriptor itself will |
| 633 | # have to do |
| 634 | pass |