/Doc/library/inspect.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 584 lines · 425 code · 159 blank · 0 comment · 0 complexity · a65556d9f052ebaed4f98e9ba18ff0d8 MD5 · raw file

  1. :mod:`inspect` --- Inspect live objects
  2. =======================================
  3. .. module:: inspect
  4. :synopsis: Extract information and source code from live objects.
  5. .. moduleauthor:: Ka-Ping Yee <ping@lfw.org>
  6. .. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
  7. .. versionadded:: 2.1
  8. The :mod:`inspect` module provides several useful functions to help get
  9. information about live objects such as modules, classes, methods, functions,
  10. tracebacks, frame objects, and code objects. For example, it can help you
  11. examine the contents of a class, retrieve the source code of a method, extract
  12. and format the argument list for a function, or get all the information you need
  13. to display a detailed traceback.
  14. There are four main kinds of services provided by this module: type checking,
  15. getting source code, inspecting classes and functions, and examining the
  16. interpreter stack.
  17. .. _inspect-types:
  18. Types and members
  19. -----------------
  20. The :func:`getmembers` function retrieves the members of an object such as a
  21. class or module. The sixteen functions whose names begin with "is" are mainly
  22. provided as convenient choices for the second argument to :func:`getmembers`.
  23. They also help you determine when you can expect to find the following special
  24. attributes:
  25. +-----------+-----------------+---------------------------+-------+
  26. | Type | Attribute | Description | Notes |
  27. +===========+=================+===========================+=======+
  28. | module | __doc__ | documentation string | |
  29. +-----------+-----------------+---------------------------+-------+
  30. | | __file__ | filename (missing for | |
  31. | | | built-in modules) | |
  32. +-----------+-----------------+---------------------------+-------+
  33. | class | __doc__ | documentation string | |
  34. +-----------+-----------------+---------------------------+-------+
  35. | | __module__ | name of module in which | |
  36. | | | this class was defined | |
  37. +-----------+-----------------+---------------------------+-------+
  38. | method | __doc__ | documentation string | |
  39. +-----------+-----------------+---------------------------+-------+
  40. | | __name__ | name with which this | |
  41. | | | method was defined | |
  42. +-----------+-----------------+---------------------------+-------+
  43. | | im_class | class object that asked | \(1) |
  44. | | | for this method | |
  45. +-----------+-----------------+---------------------------+-------+
  46. | | im_func or | function object | |
  47. | | __func__ | containing implementation | |
  48. | | | of method | |
  49. +-----------+-----------------+---------------------------+-------+
  50. | | im_self or | instance to which this | |
  51. | | __self__ | method is bound, or | |
  52. | | | ``None`` | |
  53. +-----------+-----------------+---------------------------+-------+
  54. | function | __doc__ | documentation string | |
  55. +-----------+-----------------+---------------------------+-------+
  56. | | __name__ | name with which this | |
  57. | | | function was defined | |
  58. +-----------+-----------------+---------------------------+-------+
  59. | | func_code | code object containing | |
  60. | | | compiled function | |
  61. | | | :term:`bytecode` | |
  62. +-----------+-----------------+---------------------------+-------+
  63. | | func_defaults | tuple of any default | |
  64. | | | values for arguments | |
  65. +-----------+-----------------+---------------------------+-------+
  66. | | func_doc | (same as __doc__) | |
  67. +-----------+-----------------+---------------------------+-------+
  68. | | func_globals | global namespace in which | |
  69. | | | this function was defined | |
  70. +-----------+-----------------+---------------------------+-------+
  71. | | func_name | (same as __name__) | |
  72. +-----------+-----------------+---------------------------+-------+
  73. | generator | __iter__ | defined to support | |
  74. | | | iteration over container | |
  75. +-----------+-----------------+---------------------------+-------+
  76. | | close | raises new GeneratorExit | |
  77. | | | exception inside the | |
  78. | | | generator to terminate | |
  79. | | | the iteration | |
  80. +-----------+-----------------+---------------------------+-------+
  81. | | gi_code | code object | |
  82. +-----------+-----------------+---------------------------+-------+
  83. | | gi_frame | frame object or possibly | |
  84. | | | None once the generator | |
  85. | | | has been exhausted | |
  86. +-----------+-----------------+---------------------------+-------+
  87. | | gi_running | set to 1 when generator | |
  88. | | | is executing, 0 otherwise | |
  89. +-----------+-----------------+---------------------------+-------+
  90. | | next | return the next item from | |
  91. | | | the container | |
  92. +-----------+-----------------+---------------------------+-------+
  93. | | send | resumes the generator and | |
  94. | | | "sends" a value that | |
  95. | | | becomes the result of the | |
  96. | | | current yield-expression | |
  97. +-----------+-----------------+---------------------------+-------+
  98. | | throw | used to raise an | |
  99. | | | exception inside the | |
  100. | | | generator | |
  101. +-----------+-----------------+---------------------------+-------+
  102. | traceback | tb_frame | frame object at this | |
  103. | | | level | |
  104. +-----------+-----------------+---------------------------+-------+
  105. | | tb_lasti | index of last attempted | |
  106. | | | instruction in bytecode | |
  107. +-----------+-----------------+---------------------------+-------+
  108. | | tb_lineno | current line number in | |
  109. | | | Python source code | |
  110. +-----------+-----------------+---------------------------+-------+
  111. | | tb_next | next inner traceback | |
  112. | | | object (called by this | |
  113. | | | level) | |
  114. +-----------+-----------------+---------------------------+-------+
  115. | frame | f_back | next outer frame object | |
  116. | | | (this frame's caller) | |
  117. +-----------+-----------------+---------------------------+-------+
  118. | | f_builtins | built-in namespace seen | |
  119. | | | by this frame | |
  120. +-----------+-----------------+---------------------------+-------+
  121. | | f_code | code object being | |
  122. | | | executed in this frame | |
  123. +-----------+-----------------+---------------------------+-------+
  124. | | f_exc_traceback | traceback if raised in | |
  125. | | | this frame, or ``None`` | |
  126. +-----------+-----------------+---------------------------+-------+
  127. | | f_exc_type | exception type if raised | |
  128. | | | in this frame, or | |
  129. | | | ``None`` | |
  130. +-----------+-----------------+---------------------------+-------+
  131. | | f_exc_value | exception value if raised | |
  132. | | | in this frame, or | |
  133. | | | ``None`` | |
  134. +-----------+-----------------+---------------------------+-------+
  135. | | f_globals | global namespace seen by | |
  136. | | | this frame | |
  137. +-----------+-----------------+---------------------------+-------+
  138. | | f_lasti | index of last attempted | |
  139. | | | instruction in bytecode | |
  140. +-----------+-----------------+---------------------------+-------+
  141. | | f_lineno | current line number in | |
  142. | | | Python source code | |
  143. +-----------+-----------------+---------------------------+-------+
  144. | | f_locals | local namespace seen by | |
  145. | | | this frame | |
  146. +-----------+-----------------+---------------------------+-------+
  147. | | f_restricted | 0 or 1 if frame is in | |
  148. | | | restricted execution mode | |
  149. +-----------+-----------------+---------------------------+-------+
  150. | | f_trace | tracing function for this | |
  151. | | | frame, or ``None`` | |
  152. +-----------+-----------------+---------------------------+-------+
  153. | code | co_argcount | number of arguments (not | |
  154. | | | including \* or \*\* | |
  155. | | | args) | |
  156. +-----------+-----------------+---------------------------+-------+
  157. | | co_code | string of raw compiled | |
  158. | | | bytecode | |
  159. +-----------+-----------------+---------------------------+-------+
  160. | | co_consts | tuple of constants used | |
  161. | | | in the bytecode | |
  162. +-----------+-----------------+---------------------------+-------+
  163. | | co_filename | name of file in which | |
  164. | | | this code object was | |
  165. | | | created | |
  166. +-----------+-----------------+---------------------------+-------+
  167. | | co_firstlineno | number of first line in | |
  168. | | | Python source code | |
  169. +-----------+-----------------+---------------------------+-------+
  170. | | co_flags | bitmap: 1=optimized ``|`` | |
  171. | | | 2=newlocals ``|`` 4=\*arg | |
  172. | | | ``|`` 8=\*\*arg | |
  173. +-----------+-----------------+---------------------------+-------+
  174. | | co_lnotab | encoded mapping of line | |
  175. | | | numbers to bytecode | |
  176. | | | indices | |
  177. +-----------+-----------------+---------------------------+-------+
  178. | | co_name | name with which this code | |
  179. | | | object was defined | |
  180. +-----------+-----------------+---------------------------+-------+
  181. | | co_names | tuple of names of local | |
  182. | | | variables | |
  183. +-----------+-----------------+---------------------------+-------+
  184. | | co_nlocals | number of local variables | |
  185. +-----------+-----------------+---------------------------+-------+
  186. | | co_stacksize | virtual machine stack | |
  187. | | | space required | |
  188. +-----------+-----------------+---------------------------+-------+
  189. | | co_varnames | tuple of names of | |
  190. | | | arguments and local | |
  191. | | | variables | |
  192. +-----------+-----------------+---------------------------+-------+
  193. | builtin | __doc__ | documentation string | |
  194. +-----------+-----------------+---------------------------+-------+
  195. | | __name__ | original name of this | |
  196. | | | function or method | |
  197. +-----------+-----------------+---------------------------+-------+
  198. | | __self__ | instance to which a | |
  199. | | | method is bound, or | |
  200. | | | ``None`` | |
  201. +-----------+-----------------+---------------------------+-------+
  202. Note:
  203. (1)
  204. .. versionchanged:: 2.2
  205. :attr:`im_class` used to refer to the class that defined the method.
  206. .. function:: getmembers(object[, predicate])
  207. Return all the members of an object in a list of (name, value) pairs sorted by
  208. name. If the optional *predicate* argument is supplied, only members for which
  209. the predicate returns a true value are included.
  210. .. note::
  211. :func:`getmembers` does not return metaclass attributes when the argument
  212. is a class (this behavior is inherited from the :func:`dir` function).
  213. .. function:: getmoduleinfo(path)
  214. Return a tuple of values that describe how Python will interpret the file
  215. identified by *path* if it is a module, or ``None`` if it would not be
  216. identified as a module. The return tuple is ``(name, suffix, mode, mtype)``,
  217. where *name* is the name of the module without the name of any enclosing
  218. package, *suffix* is the trailing part of the file name (which may not be a
  219. dot-delimited extension), *mode* is the :func:`open` mode that would be used
  220. (``'r'`` or ``'rb'``), and *mtype* is an integer giving the type of the
  221. module. *mtype* will have a value which can be compared to the constants
  222. defined in the :mod:`imp` module; see the documentation for that module for
  223. more information on module types.
  224. .. versionchanged:: 2.6
  225. Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode,
  226. module_type)``.
  227. .. function:: getmodulename(path)
  228. Return the name of the module named by the file *path*, without including the
  229. names of enclosing packages. This uses the same algorithm as the interpreter
  230. uses when searching for modules. If the name cannot be matched according to the
  231. interpreter's rules, ``None`` is returned.
  232. .. function:: ismodule(object)
  233. Return true if the object is a module.
  234. .. function:: isclass(object)
  235. Return true if the object is a class.
  236. .. function:: ismethod(object)
  237. Return true if the object is a method.
  238. .. function:: isfunction(object)
  239. Return true if the object is a Python function or unnamed (:term:`lambda`) function.
  240. .. function:: isgeneratorfunction(object)
  241. Return true if the object is a Python generator function.
  242. .. versionadded:: 2.6
  243. .. function:: isgenerator(object)
  244. Return true if the object is a generator.
  245. .. versionadded:: 2.6
  246. .. function:: istraceback(object)
  247. Return true if the object is a traceback.
  248. .. function:: isframe(object)
  249. Return true if the object is a frame.
  250. .. function:: iscode(object)
  251. Return true if the object is a code.
  252. .. function:: isbuiltin(object)
  253. Return true if the object is a built-in function.
  254. .. function:: isroutine(object)
  255. Return true if the object is a user-defined or built-in function or method.
  256. .. function:: isabstract(object)
  257. Return true if the object is an abstract base class.
  258. .. versionadded:: 2.6
  259. .. function:: ismethoddescriptor(object)
  260. Return true if the object is a method descriptor, but not if :func:`ismethod`
  261. or :func:`isclass` or :func:`isfunction` are true.
  262. This is new as of Python 2.2, and, for example, is true of
  263. ``int.__add__``. An object passing this test has a :attr:`__get__` attribute
  264. but not a :attr:`__set__` attribute, but beyond that the set of attributes
  265. varies. :attr:`__name__` is usually sensible, and :attr:`__doc__` often is.
  266. Methods implemented via descriptors that also pass one of the other tests
  267. return false from the :func:`ismethoddescriptor` test, simply because the
  268. other tests promise more -- you can, e.g., count on having the
  269. :attr:`im_func` attribute (etc) when an object passes :func:`ismethod`.
  270. .. function:: isdatadescriptor(object)
  271. Return true if the object is a data descriptor.
  272. Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute.
  273. Examples are properties (defined in Python), getsets, and members. The
  274. latter two are defined in C and there are more specific tests available for
  275. those types, which is robust across Python implementations. Typically, data
  276. descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes
  277. (properties, getsets, and members have both of these attributes), but this is
  278. not guaranteed.
  279. .. versionadded:: 2.3
  280. .. function:: isgetsetdescriptor(object)
  281. Return true if the object is a getset descriptor.
  282. getsets are attributes defined in extension modules via ``PyGetSetDef``
  283. structures. For Python implementations without such types, this method will
  284. always return ``False``.
  285. .. versionadded:: 2.5
  286. .. function:: ismemberdescriptor(object)
  287. Return true if the object is a member descriptor.
  288. Member descriptors are attributes defined in extension modules via
  289. ``PyMemberDef`` structures. For Python implementations without such types,
  290. this method will always return ``False``.
  291. .. versionadded:: 2.5
  292. .. _inspect-source:
  293. Retrieving source code
  294. ----------------------
  295. .. function:: getdoc(object)
  296. Get the documentation string for an object, cleaned up with :func:`cleandoc`.
  297. .. function:: getcomments(object)
  298. Return in a single string any lines of comments immediately preceding the
  299. object's source code (for a class, function, or method), or at the top of the
  300. Python source file (if the object is a module).
  301. .. function:: getfile(object)
  302. Return the name of the (text or binary) file in which an object was defined.
  303. This will fail with a :exc:`TypeError` if the object is a built-in module,
  304. class, or function.
  305. .. function:: getmodule(object)
  306. Try to guess which module an object was defined in.
  307. .. function:: getsourcefile(object)
  308. Return the name of the Python source file in which an object was defined. This
  309. will fail with a :exc:`TypeError` if the object is a built-in module, class, or
  310. function.
  311. .. function:: getsourcelines(object)
  312. Return a list of source lines and starting line number for an object. The
  313. argument may be a module, class, method, function, traceback, frame, or code
  314. object. The source code is returned as a list of the lines corresponding to the
  315. object and the line number indicates where in the original source file the first
  316. line of code was found. An :exc:`IOError` is raised if the source code cannot
  317. be retrieved.
  318. .. function:: getsource(object)
  319. Return the text of the source code for an object. The argument may be a module,
  320. class, method, function, traceback, frame, or code object. The source code is
  321. returned as a single string. An :exc:`IOError` is raised if the source code
  322. cannot be retrieved.
  323. .. function:: cleandoc(doc)
  324. Clean up indentation from docstrings that are indented to line up with blocks
  325. of code. Any whitespace that can be uniformly removed from the second line
  326. onwards is removed. Also, all tabs are expanded to spaces.
  327. .. versionadded:: 2.6
  328. .. _inspect-classes-functions:
  329. Classes and functions
  330. ---------------------
  331. .. function:: getclasstree(classes[, unique])
  332. Arrange the given list of classes into a hierarchy of nested lists. Where a
  333. nested list appears, it contains classes derived from the class whose entry
  334. immediately precedes the list. Each entry is a 2-tuple containing a class and a
  335. tuple of its base classes. If the *unique* argument is true, exactly one entry
  336. appears in the returned structure for each class in the given list. Otherwise,
  337. classes using multiple inheritance and their descendants will appear multiple
  338. times.
  339. .. function:: getargspec(func)
  340. Get the names and default values of a function's arguments. A tuple of four
  341. things is returned: ``(args, varargs, varkw, defaults)``. *args* is a list of
  342. the argument names (it may contain nested lists). *varargs* and *varkw* are the
  343. names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a tuple of
  344. default argument values or None if there are no default arguments; if this tuple
  345. has *n* elements, they correspond to the last *n* elements listed in *args*.
  346. .. versionchanged:: 2.6
  347. Returns a :term:`named tuple` ``ArgSpec(args, varargs, keywords,
  348. defaults)``.
  349. .. function:: getargvalues(frame)
  350. Get information about arguments passed into a particular frame. A tuple of four
  351. things is returned: ``(args, varargs, varkw, locals)``. *args* is a list of the
  352. argument names (it may contain nested lists). *varargs* and *varkw* are the
  353. names of the ``*`` and ``**`` arguments or ``None``. *locals* is the locals
  354. dictionary of the given frame.
  355. .. versionchanged:: 2.6
  356. Returns a :term:`named tuple` ``ArgInfo(args, varargs, keywords,
  357. locals)``.
  358. .. function:: formatargspec(args[, varargs, varkw, defaults, formatarg, formatvarargs, formatvarkw, formatvalue, join])
  359. Format a pretty argument spec from the four values returned by
  360. :func:`getargspec`. The format\* arguments are the corresponding optional
  361. formatting functions that are called to turn names and values into strings.
  362. .. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue, join])
  363. Format a pretty argument spec from the four values returned by
  364. :func:`getargvalues`. The format\* arguments are the corresponding optional
  365. formatting functions that are called to turn names and values into strings.
  366. .. function:: getmro(cls)
  367. Return a tuple of class cls's base classes, including cls, in method resolution
  368. order. No class appears more than once in this tuple. Note that the method
  369. resolution order depends on cls's type. Unless a very peculiar user-defined
  370. metatype is in use, cls will be the first element of the tuple.
  371. .. _inspect-stack:
  372. The interpreter stack
  373. ---------------------
  374. When the following functions return "frame records," each record is a tuple of
  375. six items: the frame object, the filename, the line number of the current line,
  376. the function name, a list of lines of context from the source code, and the
  377. index of the current line within that list.
  378. .. note::
  379. Keeping references to frame objects, as found in the first element of the frame
  380. records these functions return, can cause your program to create reference
  381. cycles. Once a reference cycle has been created, the lifespan of all objects
  382. which can be accessed from the objects which form the cycle can become much
  383. longer even if Python's optional cycle detector is enabled. If such cycles must
  384. be created, it is important to ensure they are explicitly broken to avoid the
  385. delayed destruction of objects and increased memory consumption which occurs.
  386. Though the cycle detector will catch these, destruction of the frames (and local
  387. variables) can be made deterministic by removing the cycle in a
  388. :keyword:`finally` clause. This is also important if the cycle detector was
  389. disabled when Python was compiled or using :func:`gc.disable`. For example::
  390. def handle_stackframe_without_leak():
  391. frame = inspect.currentframe()
  392. try:
  393. # do something with the frame
  394. finally:
  395. del frame
  396. The optional *context* argument supported by most of these functions specifies
  397. the number of lines of context to return, which are centered around the current
  398. line.
  399. .. function:: getframeinfo(frame[, context])
  400. Get information about a frame or traceback object. A 5-tuple is returned, the
  401. last five elements of the frame's frame record.
  402. .. versionchanged:: 2.6
  403. Returns a :term:`named tuple` ``Traceback(filename, lineno, function,
  404. code_context, index)``.
  405. .. function:: getouterframes(frame[, context])
  406. Get a list of frame records for a frame and all outer frames. These frames
  407. represent the calls that lead to the creation of *frame*. The first entry in the
  408. returned list represents *frame*; the last entry represents the outermost call
  409. on *frame*'s stack.
  410. .. function:: getinnerframes(traceback[, context])
  411. Get a list of frame records for a traceback's frame and all inner frames. These
  412. frames represent calls made as a consequence of *frame*. The first entry in the
  413. list represents *traceback*; the last entry represents where the exception was
  414. raised.
  415. .. function:: currentframe()
  416. Return the frame object for the caller's stack frame.
  417. .. function:: stack([context])
  418. Return a list of frame records for the caller's stack. The first entry in the
  419. returned list represents the caller; the last entry represents the outermost
  420. call on the stack.
  421. .. function:: trace([context])
  422. Return a list of frame records for the stack between the current frame and the
  423. frame in which an exception currently being handled was raised in. The first
  424. entry in the list represents the caller; the last entry represents where the
  425. exception was raised.