inspect.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. # -*- coding: iso-8859-1 -*-
  2. """Get useful information from live Python objects.
  3. This module encapsulates the interface provided by the internal special
  4. attributes (func_*, co_*, im_*, tb_*, etc.) in a friendlier fashion.
  5. It also provides some help for examining source code and class layout.
  6. Here are some of the useful functions provided by this module:
  7. ismodule(), isclass(), ismethod(), isfunction(), istraceback(),
  8. isframe(), iscode(), isbuiltin(), isroutine() - check object types
  9. getmembers() - get members of an object that satisfy a given condition
  10. getfile(), getsourcefile(), getsource() - find an object's source code
  11. getdoc(), getcomments() - get documentation on an object
  12. getmodule() - determine the module that an object came from
  13. getclasstree() - arrange classes so as to represent their hierarchy
  14. getargspec(), getargvalues() - get info about function arguments
  15. formatargspec(), formatargvalues() - format an argument spec
  16. getouterframes(), getinnerframes() - get info about frames
  17. currentframe() - get the current stack frame
  18. stack(), trace() - get info about frames on the stack or in a traceback
  19. """
  20. # This module is in the public domain. No warranties.
  21. __author__ = 'Ka-Ping Yee <[email protected]>'
  22. __date__ = '1 Jan 2001'
  23. import sys, os, types, string, re, dis, imp, tokenize, linecache
  24. # ----------------------------------------------------------- type-checking
  25. def ismodule(object):
  26. """Return true if the object is a module.
  27. Module objects provide these attributes:
  28. __doc__ documentation string
  29. __file__ filename (missing for built-in modules)"""
  30. return isinstance(object, types.ModuleType)
  31. def isclass(object):
  32. """Return true if the object is a class.
  33. Class objects provide these attributes:
  34. __doc__ documentation string
  35. __module__ name of module in which this class was defined"""
  36. return isinstance(object, types.ClassType) or hasattr(object, '__bases__')
  37. def ismethod(object):
  38. """Return true if the object is an instance method.
  39. Instance method objects provide these attributes:
  40. __doc__ documentation string
  41. __name__ name with which this method was defined
  42. im_class class object in which this method belongs
  43. im_func function object containing implementation of method
  44. im_self instance to which this method is bound, or None"""
  45. return isinstance(object, types.MethodType)
  46. def ismethoddescriptor(object):
  47. """Return true if the object is a method descriptor.
  48. But not if ismethod() or isclass() or isfunction() are true.
  49. This is new in Python 2.2, and, for example, is true of int.__add__.
  50. An object passing this test has a __get__ attribute but not a __set__
  51. attribute, but beyond that the set of attributes varies. __name__ is
  52. usually sensible, and __doc__ often is.
  53. Methods implemented via descriptors that also pass one of the other
  54. tests return false from the ismethoddescriptor() test, simply because
  55. the other tests promise more -- you can, e.g., count on having the
  56. im_func attribute (etc) when an object passes ismethod()."""
  57. return (hasattr(object, "__get__")
  58. and not hasattr(object, "__set__") # else it's a data descriptor
  59. and not ismethod(object) # mutual exclusion
  60. and not isfunction(object)
  61. and not isclass(object))
  62. def isdatadescriptor(object):
  63. """Return true if the object is a data descriptor.
  64. Data descriptors have both a __get__ and a __set__ attribute. Examples are
  65. properties (defined in Python) and getsets and members (defined in C).
  66. Typically, data descriptors will also have __name__ and __doc__ attributes
  67. (properties, getsets, and members have both of these attributes), but this
  68. is not guaranteed."""
  69. return (hasattr(object, "__set__") and hasattr(object, "__get__"))
  70. def isfunction(object):
  71. """Return true if the object is a user-defined function.
  72. Function objects provide these attributes:
  73. __doc__ documentation string
  74. __name__ name with which this function was defined
  75. func_code code object containing compiled function bytecode
  76. func_defaults tuple of any default values for arguments
  77. func_doc (same as __doc__)
  78. func_globals global namespace in which this function was defined
  79. func_name (same as __name__)"""
  80. return isinstance(object, types.FunctionType)
  81. def istraceback(object):
  82. """Return true if the object is a traceback.
  83. Traceback objects provide these attributes:
  84. tb_frame frame object at this level
  85. tb_lasti index of last attempted instruction in bytecode
  86. tb_lineno current line number in Python source code
  87. tb_next next inner traceback object (called by this level)"""
  88. return isinstance(object, types.TracebackType)
  89. def isframe(object):
  90. """Return true if the object is a frame object.
  91. Frame objects provide these attributes:
  92. f_back next outer frame object (this frame's caller)
  93. f_builtins built-in namespace seen by this frame
  94. f_code code object being executed in this frame
  95. f_exc_traceback traceback if raised in this frame, or None
  96. f_exc_type exception type if raised in this frame, or None
  97. f_exc_value exception value if raised in this frame, or None
  98. f_globals global namespace seen by this frame
  99. f_lasti index of last attempted instruction in bytecode
  100. f_lineno current line number in Python source code
  101. f_locals local namespace seen by this frame
  102. f_restricted 0 or 1 if frame is in restricted execution mode
  103. f_trace tracing function for this frame, or None"""
  104. return isinstance(object, types.FrameType)
  105. def iscode(object):
  106. """Return true if the object is a code object.
  107. Code objects provide these attributes:
  108. co_argcount number of arguments (not including * or ** args)
  109. co_code string of raw compiled bytecode
  110. co_consts tuple of constants used in the bytecode
  111. co_filename name of file in which this code object was created
  112. co_firstlineno number of first line in Python source code
  113. co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
  114. co_lnotab encoded mapping of line numbers to bytecode indices
  115. co_name name with which this code object was defined
  116. co_names tuple of names of local variables
  117. co_nlocals number of local variables
  118. co_stacksize virtual machine stack space required
  119. co_varnames tuple of names of arguments and local variables"""
  120. return isinstance(object, types.CodeType)
  121. def isbuiltin(object):
  122. """Return true if the object is a built-in function or method.
  123. Built-in functions and methods provide these attributes:
  124. __doc__ documentation string
  125. __name__ original name of this function or method
  126. __self__ instance to which a method is bound, or None"""
  127. return isinstance(object, types.BuiltinFunctionType)
  128. def isroutine(object):
  129. """Return true if the object is any kind of function or method."""
  130. return (isbuiltin(object)
  131. or isfunction(object)
  132. or ismethod(object)
  133. or ismethoddescriptor(object))
  134. def getmembers(object, predicate=None):
  135. """Return all members of an object as (name, value) pairs sorted by name.
  136. Optionally, only return members that satisfy a given predicate."""
  137. results = []
  138. for key in dir(object):
  139. value = getattr(object, key)
  140. if not predicate or predicate(value):
  141. results.append((key, value))
  142. results.sort()
  143. return results
  144. def classify_class_attrs(cls):
  145. """Return list of attribute-descriptor tuples.
  146. For each name in dir(cls), the return list contains a 4-tuple
  147. with these elements:
  148. 0. The name (a string).
  149. 1. The kind of attribute this is, one of these strings:
  150. 'class method' created via classmethod()
  151. 'static method' created via staticmethod()
  152. 'property' created via property()
  153. 'method' any other flavor of method
  154. 'data' not a method
  155. 2. The class which defined this attribute (a class).
  156. 3. The object as obtained directly from the defining class's
  157. __dict__, not via getattr. This is especially important for
  158. data attributes: C.data is just a data object, but
  159. C.__dict__['data'] may be a data descriptor with additional
  160. info, like a __doc__ string.
  161. """
  162. mro = getmro(cls)
  163. names = dir(cls)
  164. result = []
  165. for name in names:
  166. # Get the object associated with the name.
  167. # Getting an obj from the __dict__ sometimes reveals more than
  168. # using getattr. Static and class methods are dramatic examples.
  169. if name in cls.__dict__:
  170. obj = cls.__dict__[name]
  171. else:
  172. obj = getattr(cls, name)
  173. # Figure out where it was defined.
  174. homecls = getattr(obj, "__objclass__", None)
  175. if homecls is None:
  176. # search the dicts.
  177. for base in mro:
  178. if name in base.__dict__:
  179. homecls = base
  180. break
  181. # Get the object again, in order to get it from the defining
  182. # __dict__ instead of via getattr (if possible).
  183. if homecls is not None and name in homecls.__dict__:
  184. obj = homecls.__dict__[name]
  185. # Also get the object via getattr.
  186. obj_via_getattr = getattr(cls, name)
  187. # Classify the object.
  188. if isinstance(obj, staticmethod):
  189. kind = "static method"
  190. elif isinstance(obj, classmethod):
  191. kind = "class method"
  192. elif isinstance(obj, property):
  193. kind = "property"
  194. elif (ismethod(obj_via_getattr) or
  195. ismethoddescriptor(obj_via_getattr)):
  196. kind = "method"
  197. else:
  198. kind = "data"
  199. result.append((name, kind, homecls, obj))
  200. return result
  201. # ----------------------------------------------------------- class helpers
  202. def _searchbases(cls, accum):
  203. # Simulate the "classic class" search order.
  204. if cls in accum:
  205. return
  206. accum.append(cls)
  207. for base in cls.__bases__:
  208. _searchbases(base, accum)
  209. def getmro(cls):
  210. "Return tuple of base classes (including cls) in method resolution order."
  211. if hasattr(cls, "__mro__"):
  212. return cls.__mro__
  213. else:
  214. result = []
  215. _searchbases(cls, result)
  216. return tuple(result)
  217. # -------------------------------------------------- source code extraction
  218. def indentsize(line):
  219. """Return the indent size, in spaces, at the start of a line of text."""
  220. expline = string.expandtabs(line)
  221. return len(expline) - len(string.lstrip(expline))
  222. def getdoc(object):
  223. """Get the documentation string for an object.
  224. All tabs are expanded to spaces. To clean up docstrings that are
  225. indented to line up with blocks of code, any whitespace than can be
  226. uniformly removed from the second line onwards is removed."""
  227. try:
  228. doc = object.__doc__
  229. except AttributeError:
  230. return None
  231. if not isinstance(doc, types.StringTypes):
  232. return None
  233. try:
  234. lines = string.split(string.expandtabs(doc), '\n')
  235. except UnicodeError:
  236. return None
  237. else:
  238. # Find minimum indentation of any non-blank lines after first line.
  239. margin = sys.maxint
  240. for line in lines[1:]:
  241. content = len(string.lstrip(line))
  242. if content:
  243. indent = len(line) - content
  244. margin = min(margin, indent)
  245. # Remove indentation.
  246. if lines:
  247. lines[0] = lines[0].lstrip()
  248. if margin < sys.maxint:
  249. for i in range(1, len(lines)): lines[i] = lines[i][margin:]
  250. # Remove any trailing or leading blank lines.
  251. while lines and not lines[-1]:
  252. lines.pop()
  253. while lines and not lines[0]:
  254. lines.pop(0)
  255. return string.join(lines, '\n')
  256. def getfile(object):
  257. """Work out which source or compiled file an object was defined in."""
  258. if ismodule(object):
  259. if hasattr(object, '__file__'):
  260. return object.__file__
  261. raise TypeError('arg is a built-in module')
  262. if isclass(object):
  263. object = sys.modules.get(object.__module__)
  264. if hasattr(object, '__file__'):
  265. return object.__file__
  266. raise TypeError('arg is a built-in class')
  267. if ismethod(object):
  268. object = object.im_func
  269. if isfunction(object):
  270. object = object.func_code
  271. if istraceback(object):
  272. object = object.tb_frame
  273. if isframe(object):
  274. object = object.f_code
  275. if iscode(object):
  276. return object.co_filename
  277. raise TypeError('arg is not a module, class, method, '
  278. 'function, traceback, frame, or code object')
  279. def getmoduleinfo(path):
  280. """Get the module name, suffix, mode, and module type for a given file."""
  281. filename = os.path.basename(path)
  282. suffixes = map(lambda (suffix, mode, mtype):
  283. (-len(suffix), suffix, mode, mtype), imp.get_suffixes())
  284. suffixes.sort() # try longest suffixes first, in case they overlap
  285. for neglen, suffix, mode, mtype in suffixes:
  286. if filename[neglen:] == suffix:
  287. return filename[:neglen], suffix, mode, mtype
  288. def getmodulename(path):
  289. """Return the module name for a given file, or None."""
  290. info = getmoduleinfo(path)
  291. if info: return info[0]
  292. def getsourcefile(object):
  293. """Return the Python source file an object was defined in, if it exists."""
  294. filename = getfile(object)
  295. if string.lower(filename[-4:]) in ['.pyc', '.pyo']:
  296. filename = filename[:-4] + '.py'
  297. for suffix, mode, kind in imp.get_suffixes():
  298. if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
  299. # Looks like a binary file. We want to only return a text file.
  300. return None
  301. if os.path.exists(filename):
  302. return filename
  303. def getabsfile(object):
  304. """Return an absolute path to the source or compiled file for an object.
  305. The idea is for each object to have a unique origin, so this routine
  306. normalizes the result as much as possible."""
  307. return os.path.normcase(
  308. os.path.abspath(getsourcefile(object) or getfile(object)))
  309. modulesbyfile = {}
  310. def getmodule(object):
  311. """Return the module an object was defined in, or None if not found."""
  312. if ismodule(object):
  313. return object
  314. if hasattr(object, '__module__'):
  315. return sys.modules.get(object.__module__)
  316. try:
  317. file = getabsfile(object)
  318. except TypeError:
  319. return None
  320. if file in modulesbyfile:
  321. return sys.modules.get(modulesbyfile[file])
  322. for module in sys.modules.values():
  323. if hasattr(module, '__file__'):
  324. modulesbyfile[
  325. os.path.realpath(
  326. getabsfile(module))] = module.__name__
  327. if file in modulesbyfile:
  328. return sys.modules.get(modulesbyfile[file])
  329. main = sys.modules['__main__']
  330. if not hasattr(object, '__name__'):
  331. return None
  332. if hasattr(main, object.__name__):
  333. mainobject = getattr(main, object.__name__)
  334. if mainobject is object:
  335. return main
  336. builtin = sys.modules['__builtin__']
  337. if hasattr(builtin, object.__name__):
  338. builtinobject = getattr(builtin, object.__name__)
  339. if builtinobject is object:
  340. return builtin
  341. def findsource(object):
  342. """Return the entire source file and starting line number for an object.
  343. The argument may be a module, class, method, function, traceback, frame,
  344. or code object. The source code is returned as a list of all the lines
  345. in the file and the line number indexes a line in that list. An IOError
  346. is raised if the source code cannot be retrieved."""
  347. file = getsourcefile(object) or getfile(object)
  348. lines = linecache.getlines(file)
  349. if not lines:
  350. raise IOError('could not get source code')
  351. if ismodule(object):
  352. return lines, 0
  353. if isclass(object):
  354. name = object.__name__
  355. pat = re.compile(r'^\s*class\s*' + name + r'\b')
  356. for i in range(len(lines)):
  357. if pat.match(lines[i]): return lines, i
  358. else:
  359. raise IOError('could not find class definition')
  360. if ismethod(object):
  361. object = object.im_func
  362. if isfunction(object):
  363. object = object.func_code
  364. if istraceback(object):
  365. object = object.tb_frame
  366. if isframe(object):
  367. object = object.f_code
  368. if iscode(object):
  369. if not hasattr(object, 'co_firstlineno'):
  370. raise IOError('could not find function definition')
  371. lnum = object.co_firstlineno - 1
  372. pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
  373. while lnum > 0:
  374. if pat.match(lines[lnum]): break
  375. lnum = lnum - 1
  376. return lines, lnum
  377. raise IOError('could not find code object')
  378. def getcomments(object):
  379. """Get lines of comments immediately preceding an object's source code.
  380. Returns None when source can't be found.
  381. """
  382. try:
  383. lines, lnum = findsource(object)
  384. except (IOError, TypeError):
  385. return None
  386. if ismodule(object):
  387. # Look for a comment block at the top of the file.
  388. start = 0
  389. if lines and lines[0][:2] == '#!': start = 1
  390. while start < len(lines) and string.strip(lines[start]) in ['', '#']:
  391. start = start + 1
  392. if start < len(lines) and lines[start][:1] == '#':
  393. comments = []
  394. end = start
  395. while end < len(lines) and lines[end][:1] == '#':
  396. comments.append(string.expandtabs(lines[end]))
  397. end = end + 1
  398. return string.join(comments, '')
  399. # Look for a preceding block of comments at the same indentation.
  400. elif lnum > 0:
  401. indent = indentsize(lines[lnum])
  402. end = lnum - 1
  403. if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \
  404. indentsize(lines[end]) == indent:
  405. comments = [string.lstrip(string.expandtabs(lines[end]))]
  406. if end > 0:
  407. end = end - 1
  408. comment = string.lstrip(string.expandtabs(lines[end]))
  409. while comment[:1] == '#' and indentsize(lines[end]) == indent:
  410. comments[:0] = [comment]
  411. end = end - 1
  412. if end < 0: break
  413. comment = string.lstrip(string.expandtabs(lines[end]))
  414. while comments and string.strip(comments[0]) == '#':
  415. comments[:1] = []
  416. while comments and string.strip(comments[-1]) == '#':
  417. comments[-1:] = []
  418. return string.join(comments, '')
  419. class EndOfBlock(Exception): pass
  420. class BlockFinder:
  421. """Provide a tokeneater() method to detect the end of a code block."""
  422. def __init__(self):
  423. self.indent = 0
  424. self.islambda = False
  425. self.started = False
  426. self.passline = False
  427. self.last = 1
  428. def tokeneater(self, type, token, (srow, scol), (erow, ecol), line):
  429. if not self.started:
  430. # look for the first "def", "class" or "lambda"
  431. if token in ("def", "class", "lambda"):
  432. if token == "lambda":
  433. self.islambda = True
  434. self.started = True
  435. self.passline = True # skip to the end of the line
  436. elif type == tokenize.NEWLINE:
  437. self.passline = False # stop skipping when a NEWLINE is seen
  438. self.last = srow
  439. if self.islambda: # lambdas always end at the first NEWLINE
  440. raise EndOfBlock
  441. elif self.passline:
  442. pass
  443. elif type == tokenize.INDENT:
  444. self.indent = self.indent + 1
  445. self.passline = True
  446. elif type == tokenize.DEDENT:
  447. self.indent = self.indent - 1
  448. # the end of matching indent/dedent pairs end a block
  449. # (note that this only works for "def"/"class" blocks,
  450. # not e.g. for "if: else:" or "try: finally:" blocks)
  451. if self.indent <= 0:
  452. raise EndOfBlock
  453. elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
  454. # any other token on the same indentation level end the previous
  455. # block as well, except the pseudo-tokens COMMENT and NL.
  456. raise EndOfBlock
  457. def getblock(lines):
  458. """Extract the block of code at the top of the given list of lines."""
  459. blockfinder = BlockFinder()
  460. try:
  461. tokenize.tokenize(iter(lines).next, blockfinder.tokeneater)
  462. except (EndOfBlock, IndentationError):
  463. pass
  464. return lines[:blockfinder.last]
  465. def getsourcelines(object):
  466. """Return a list of source lines and starting line number for an object.
  467. The argument may be a module, class, method, function, traceback, frame,
  468. or code object. The source code is returned as a list of the lines
  469. corresponding to the object and the line number indicates where in the
  470. original source file the first line of code was found. An IOError is
  471. raised if the source code cannot be retrieved."""
  472. lines, lnum = findsource(object)
  473. if ismodule(object): return lines, 0
  474. else: return getblock(lines[lnum:]), lnum + 1
  475. def getsource(object):
  476. """Return the text of the source code for an object.
  477. The argument may be a module, class, method, function, traceback, frame,
  478. or code object. The source code is returned as a single string. An
  479. IOError is raised if the source code cannot be retrieved."""
  480. lines, lnum = getsourcelines(object)
  481. return string.join(lines, '')
  482. # --------------------------------------------------- class tree extraction
  483. def walktree(classes, children, parent):
  484. """Recursive helper function for getclasstree()."""
  485. results = []
  486. classes.sort(key=lambda c: (c.__module__, c.__name__))
  487. for c in classes:
  488. results.append((c, c.__bases__))
  489. if c in children:
  490. results.append(walktree(children[c], children, c))
  491. return results
  492. def getclasstree(classes, unique=0):
  493. """Arrange the given list of classes into a hierarchy of nested lists.
  494. Where a nested list appears, it contains classes derived from the class
  495. whose entry immediately precedes the list. Each entry is a 2-tuple
  496. containing a class and a tuple of its base classes. If the 'unique'
  497. argument is true, exactly one entry appears in the returned structure
  498. for each class in the given list. Otherwise, classes using multiple
  499. inheritance and their descendants will appear multiple times."""
  500. children = {}
  501. roots = []
  502. for c in classes:
  503. if c.__bases__:
  504. for parent in c.__bases__:
  505. if not parent in children:
  506. children[parent] = []
  507. children[parent].append(c)
  508. if unique and parent in classes: break
  509. elif c not in roots:
  510. roots.append(c)
  511. for parent in children:
  512. if parent not in classes:
  513. roots.append(parent)
  514. return walktree(roots, children, None)
  515. # ------------------------------------------------ argument list extraction
  516. # These constants are from Python's compile.h.
  517. CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8
  518. def getargs(co):
  519. """Get information about the arguments accepted by a code object.
  520. Three things are returned: (args, varargs, varkw), where 'args' is
  521. a list of argument names (possibly containing nested lists), and
  522. 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
  523. if not iscode(co):
  524. raise TypeError('arg is not a code object')
  525. code = co.co_code
  526. nargs = co.co_argcount
  527. names = co.co_varnames
  528. args = list(names[:nargs])
  529. step = 0
  530. # The following acrobatics are for anonymous (tuple) arguments.
  531. for i in range(nargs):
  532. if args[i][:1] in ['', '.']:
  533. stack, remain, count = [], [], []
  534. while step < len(code):
  535. op = ord(code[step])
  536. step = step + 1
  537. if op >= dis.HAVE_ARGUMENT:
  538. opname = dis.opname[op]
  539. value = ord(code[step]) + ord(code[step+1])*256
  540. step = step + 2
  541. if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']:
  542. remain.append(value)
  543. count.append(value)
  544. elif opname == 'STORE_FAST':
  545. stack.append(names[value])
  546. # Special case for sublists of length 1: def foo((bar))
  547. # doesn't generate the UNPACK_TUPLE bytecode, so if
  548. # `remain` is empty here, we have such a sublist.
  549. if not remain:
  550. stack[0] = [stack[0]]
  551. break
  552. else:
  553. remain[-1] = remain[-1] - 1
  554. while remain[-1] == 0:
  555. remain.pop()
  556. size = count.pop()
  557. stack[-size:] = [stack[-size:]]
  558. if not remain: break
  559. remain[-1] = remain[-1] - 1
  560. if not remain: break
  561. args[i] = stack[0]
  562. varargs = None
  563. if co.co_flags & CO_VARARGS:
  564. varargs = co.co_varnames[nargs]
  565. nargs = nargs + 1
  566. varkw = None
  567. if co.co_flags & CO_VARKEYWORDS:
  568. varkw = co.co_varnames[nargs]
  569. return args, varargs, varkw
  570. def getargspec(func):
  571. """Get the names and default values of a function's arguments.
  572. A tuple of four things is returned: (args, varargs, varkw, defaults).
  573. 'args' is a list of the argument names (it may contain nested lists).
  574. 'varargs' and 'varkw' are the names of the * and ** arguments or None.
  575. 'defaults' is an n-tuple of the default values of the last n arguments.
  576. """
  577. if ismethod(func):
  578. func = func.im_func
  579. if not isfunction(func):
  580. raise TypeError('arg is not a Python function')
  581. args, varargs, varkw = getargs(func.func_code)
  582. return args, varargs, varkw, func.func_defaults
  583. def getargvalues(frame):
  584. """Get information about arguments passed into a particular frame.
  585. A tuple of four things is returned: (args, varargs, varkw, locals).
  586. 'args' is a list of the argument names (it may contain nested lists).
  587. 'varargs' and 'varkw' are the names of the * and ** arguments or None.
  588. 'locals' is the locals dictionary of the given frame."""
  589. args, varargs, varkw = getargs(frame.f_code)
  590. return args, varargs, varkw, frame.f_locals
  591. def joinseq(seq):
  592. if len(seq) == 1:
  593. return '(' + seq[0] + ',)'
  594. else:
  595. return '(' + string.join(seq, ', ') + ')'
  596. def strseq(object, convert, join=joinseq):
  597. """Recursively walk a sequence, stringifying each element."""
  598. if type(object) in [types.ListType, types.TupleType]:
  599. return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
  600. else:
  601. return convert(object)
  602. def formatargspec(args, varargs=None, varkw=None, defaults=None,
  603. formatarg=str,
  604. formatvarargs=lambda name: '*' + name,
  605. formatvarkw=lambda name: '**' + name,
  606. formatvalue=lambda value: '=' + repr(value),
  607. join=joinseq):
  608. """Format an argument spec from the 4 values returned by getargspec.
  609. The first four arguments are (args, varargs, varkw, defaults). The
  610. other four arguments are the corresponding optional formatting functions
  611. that are called to turn names and values into strings. The ninth
  612. argument is an optional function to format the sequence of arguments."""
  613. specs = []
  614. if defaults:
  615. firstdefault = len(args) - len(defaults)
  616. for i in range(len(args)):
  617. spec = strseq(args[i], formatarg, join)
  618. if defaults and i >= firstdefault:
  619. spec = spec + formatvalue(defaults[i - firstdefault])
  620. specs.append(spec)
  621. if varargs is not None:
  622. specs.append(formatvarargs(varargs))
  623. if varkw is not None:
  624. specs.append(formatvarkw(varkw))
  625. return '(' + string.join(specs, ', ') + ')'
  626. def formatargvalues(args, varargs, varkw, locals,
  627. formatarg=str,
  628. formatvarargs=lambda name: '*' + name,
  629. formatvarkw=lambda name: '**' + name,
  630. formatvalue=lambda value: '=' + repr(value),
  631. join=joinseq):
  632. """Format an argument spec from the 4 values returned by getargvalues.
  633. The first four arguments are (args, varargs, varkw, locals). The
  634. next four arguments are the corresponding optional formatting functions
  635. that are called to turn names and values into strings. The ninth
  636. argument is an optional function to format the sequence of arguments."""
  637. def convert(name, locals=locals,
  638. formatarg=formatarg, formatvalue=formatvalue):
  639. return formatarg(name) + formatvalue(locals[name])
  640. specs = []
  641. for i in range(len(args)):
  642. specs.append(strseq(args[i], convert, join))
  643. if varargs:
  644. specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
  645. if varkw:
  646. specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
  647. return '(' + string.join(specs, ', ') + ')'
  648. # -------------------------------------------------- stack frame extraction
  649. def getframeinfo(frame, context=1):
  650. """Get information about a frame or traceback object.
  651. A tuple of five things is returned: the filename, the line number of
  652. the current line, the function name, a list of lines of context from
  653. the source code, and the index of the current line within that list.
  654. The optional second argument specifies the number of lines of context
  655. to return, which are centered around the current line."""
  656. if istraceback(frame):
  657. lineno = frame.tb_lineno
  658. frame = frame.tb_frame
  659. else:
  660. lineno = frame.f_lineno
  661. if not isframe(frame):
  662. raise TypeError('arg is not a frame or traceback object')
  663. filename = getsourcefile(frame) or getfile(frame)
  664. if context > 0:
  665. start = lineno - 1 - context//2
  666. try:
  667. lines, lnum = findsource(frame)
  668. except IOError:
  669. lines = index = None
  670. else:
  671. start = max(start, 1)
  672. start = max(0, min(start, len(lines) - context))
  673. lines = lines[start:start+context]
  674. index = lineno - 1 - start
  675. else:
  676. lines = index = None
  677. return (filename, lineno, frame.f_code.co_name, lines, index)
  678. def getlineno(frame):
  679. """Get the line number from a frame object, allowing for optimization."""
  680. # FrameType.f_lineno is now a descriptor that grovels co_lnotab
  681. return frame.f_lineno
  682. def getouterframes(frame, context=1):
  683. """Get a list of records for a frame and all higher (calling) frames.
  684. Each record contains a frame object, filename, line number, function
  685. name, a list of lines of context, and index within the context."""
  686. framelist = []
  687. while frame:
  688. framelist.append((frame,) + getframeinfo(frame, context))
  689. frame = frame.f_back
  690. return framelist
  691. def getinnerframes(tb, context=1):
  692. """Get a list of records for a traceback's frame and all lower frames.
  693. Each record contains a frame object, filename, line number, function
  694. name, a list of lines of context, and index within the context."""
  695. framelist = []
  696. while tb:
  697. framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
  698. tb = tb.tb_next
  699. return framelist
  700. currentframe = sys._getframe
  701. def stack(context=1):
  702. """Return a list of records for the stack above the caller's frame."""
  703. return getouterframes(sys._getframe(1), context)
  704. def trace(context=1):
  705. """Return a list of records for the stack below the current exception."""
  706. return getinnerframes(sys.exc_info()[2], context)