PageRenderTime 56ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/Python/system/inspect.py

https://bitbucket.org/cwalther/moulscript-dlanor
Python | 799 lines | 750 code | 5 blank | 44 comment | 15 complexity | 34f81006098e5042c4785cf903b81df5 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-3.0
  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 <ping@lfw.org>'
  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 isclass(object):
  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[getabsfile(module)] = module.__name__
  325. if file in modulesbyfile:
  326. return sys.modules.get(modulesbyfile[file])
  327. main = sys.modules['__main__']
  328. if not hasattr(object, '__name__'):
  329. return None
  330. if hasattr(main, object.__name__):
  331. mainobject = getattr(main, object.__name__)
  332. if mainobject is object:
  333. return main
  334. builtin = sys.modules['__builtin__']
  335. if hasattr(builtin, object.__name__):
  336. builtinobject = getattr(builtin, object.__name__)
  337. if builtinobject is object:
  338. return builtin
  339. def findsource(object):
  340. """Return the entire source file and starting line number for an object.
  341. The argument may be a module, class, method, function, traceback, frame,
  342. or code object. The source code is returned as a list of all the lines
  343. in the file and the line number indexes a line in that list. An IOError
  344. is raised if the source code cannot be retrieved."""
  345. file = getsourcefile(object) or getfile(object)
  346. lines = linecache.getlines(file)
  347. if not lines:
  348. raise IOError('could not get source code')
  349. if ismodule(object):
  350. return lines, 0
  351. if isclass(object):
  352. name = object.__name__
  353. pat = re.compile(r'^\s*class\s*' + name + r'\b')
  354. for i in range(len(lines)):
  355. if pat.match(lines[i]): return lines, i
  356. else:
  357. raise IOError('could not find class definition')
  358. if ismethod(object):
  359. object = object.im_func
  360. if isfunction(object):
  361. object = object.func_code
  362. if istraceback(object):
  363. object = object.tb_frame
  364. if isframe(object):
  365. object = object.f_code
  366. if iscode(object):
  367. if not hasattr(object, 'co_firstlineno'):
  368. raise IOError('could not find function definition')
  369. lnum = object.co_firstlineno - 1
  370. pat = re.compile(r'^(\s*def\s)|(.*\slambda(:|\s))')
  371. while lnum > 0:
  372. if pat.match(lines[lnum]): break
  373. lnum = lnum - 1
  374. return lines, lnum
  375. raise IOError('could not find code object')
  376. def getcomments(object):
  377. """Get lines of comments immediately preceding an object's source code.
  378. Returns None when source can't be found.
  379. """
  380. try:
  381. lines, lnum = findsource(object)
  382. except (IOError, TypeError):
  383. return None
  384. if ismodule(object):
  385. # Look for a comment block at the top of the file.
  386. start = 0
  387. if lines and lines[0][:2] == '#!': start = 1
  388. while start < len(lines) and string.strip(lines[start]) in ['', '#']:
  389. start = start + 1
  390. if start < len(lines) and lines[start][:1] == '#':
  391. comments = []
  392. end = start
  393. while end < len(lines) and lines[end][:1] == '#':
  394. comments.append(string.expandtabs(lines[end]))
  395. end = end + 1
  396. return string.join(comments, '')
  397. # Look for a preceding block of comments at the same indentation.
  398. elif lnum > 0:
  399. indent = indentsize(lines[lnum])
  400. end = lnum - 1
  401. if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \
  402. indentsize(lines[end]) == indent:
  403. comments = [string.lstrip(string.expandtabs(lines[end]))]
  404. if end > 0:
  405. end = end - 1
  406. comment = string.lstrip(string.expandtabs(lines[end]))
  407. while comment[:1] == '#' and indentsize(lines[end]) == indent:
  408. comments[:0] = [comment]
  409. end = end - 1
  410. if end < 0: break
  411. comment = string.lstrip(string.expandtabs(lines[end]))
  412. while comments and string.strip(comments[0]) == '#':
  413. comments[:1] = []
  414. while comments and string.strip(comments[-1]) == '#':
  415. comments[-1:] = []
  416. return string.join(comments, '')
  417. class ListReader:
  418. """Provide a readline() method to return lines from a list of strings."""
  419. def __init__(self, lines):
  420. self.lines = lines
  421. self.index = 0
  422. def readline(self):
  423. i = self.index
  424. if i < len(self.lines):
  425. self.index = i + 1
  426. return self.lines[i]
  427. else: return ''
  428. class EndOfBlock(Exception): pass
  429. class BlockFinder:
  430. """Provide a tokeneater() method to detect the end of a code block."""
  431. def __init__(self):
  432. self.indent = 0
  433. self.started = 0
  434. self.last = 0
  435. def tokeneater(self, type, token, (srow, scol), (erow, ecol), line):
  436. if not self.started:
  437. if type == tokenize.NAME: self.started = 1
  438. elif type == tokenize.NEWLINE:
  439. self.last = srow
  440. elif type == tokenize.INDENT:
  441. self.indent = self.indent + 1
  442. elif type == tokenize.DEDENT:
  443. self.indent = self.indent - 1
  444. if self.indent == 0:
  445. raise EndOfBlock, self.last
  446. elif type == tokenize.NAME and scol == 0:
  447. raise EndOfBlock, self.last
  448. def getblock(lines):
  449. """Extract the block of code at the top of the given list of lines."""
  450. try:
  451. tokenize.tokenize(ListReader(lines).readline, BlockFinder().tokeneater)
  452. except EndOfBlock, eob:
  453. return lines[:eob.args[0]]
  454. # Fooling the indent/dedent logic implies a one-line definition
  455. return lines[:1]
  456. def getsourcelines(object):
  457. """Return a list of source lines and starting line number for an object.
  458. The argument may be a module, class, method, function, traceback, frame,
  459. or code object. The source code is returned as a list of the lines
  460. corresponding to the object and the line number indicates where in the
  461. original source file the first line of code was found. An IOError is
  462. raised if the source code cannot be retrieved."""
  463. lines, lnum = findsource(object)
  464. if ismodule(object): return lines, 0
  465. else: return getblock(lines[lnum:]), lnum + 1
  466. def getsource(object):
  467. """Return the text of the source code for an object.
  468. The argument may be a module, class, method, function, traceback, frame,
  469. or code object. The source code is returned as a single string. An
  470. IOError is raised if the source code cannot be retrieved."""
  471. lines, lnum = getsourcelines(object)
  472. return string.join(lines, '')
  473. # --------------------------------------------------- class tree extraction
  474. def walktree(classes, children, parent):
  475. """Recursive helper function for getclasstree()."""
  476. results = []
  477. classes.sort(lambda a, b: cmp(a.__name__, b.__name__))
  478. for c in classes:
  479. results.append((c, c.__bases__))
  480. if c in children:
  481. results.append(walktree(children[c], children, c))
  482. return results
  483. def getclasstree(classes, unique=0):
  484. """Arrange the given list of classes into a hierarchy of nested lists.
  485. Where a nested list appears, it contains classes derived from the class
  486. whose entry immediately precedes the list. Each entry is a 2-tuple
  487. containing a class and a tuple of its base classes. If the 'unique'
  488. argument is true, exactly one entry appears in the returned structure
  489. for each class in the given list. Otherwise, classes using multiple
  490. inheritance and their descendants will appear multiple times."""
  491. children = {}
  492. roots = []
  493. for c in classes:
  494. if c.__bases__:
  495. for parent in c.__bases__:
  496. if not parent in children:
  497. children[parent] = []
  498. children[parent].append(c)
  499. if unique and parent in classes: break
  500. elif c not in roots:
  501. roots.append(c)
  502. for parent in children:
  503. if parent not in classes:
  504. roots.append(parent)
  505. return walktree(roots, children, None)
  506. # ------------------------------------------------ argument list extraction
  507. # These constants are from Python's compile.h.
  508. CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8
  509. def getargs(co):
  510. """Get information about the arguments accepted by a code object.
  511. Three things are returned: (args, varargs, varkw), where 'args' is
  512. a list of argument names (possibly containing nested lists), and
  513. 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
  514. if not iscode(co):
  515. raise TypeError('arg is not a code object')
  516. code = co.co_code
  517. nargs = co.co_argcount
  518. names = co.co_varnames
  519. args = list(names[:nargs])
  520. step = 0
  521. # The following acrobatics are for anonymous (tuple) arguments.
  522. for i in range(nargs):
  523. if args[i][:1] in ['', '.']:
  524. stack, remain, count = [], [], []
  525. while step < len(code):
  526. op = ord(code[step])
  527. step = step + 1
  528. if op >= dis.HAVE_ARGUMENT:
  529. opname = dis.opname[op]
  530. value = ord(code[step]) + ord(code[step+1])*256
  531. step = step + 2
  532. if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']:
  533. remain.append(value)
  534. count.append(value)
  535. elif opname == 'STORE_FAST':
  536. stack.append(names[value])
  537. remain[-1] = remain[-1] - 1
  538. while remain[-1] == 0:
  539. remain.pop()
  540. size = count.pop()
  541. stack[-size:] = [stack[-size:]]
  542. if not remain: break
  543. remain[-1] = remain[-1] - 1
  544. if not remain: break
  545. args[i] = stack[0]
  546. varargs = None
  547. if co.co_flags & CO_VARARGS:
  548. varargs = co.co_varnames[nargs]
  549. nargs = nargs + 1
  550. varkw = None
  551. if co.co_flags & CO_VARKEYWORDS:
  552. varkw = co.co_varnames[nargs]
  553. return args, varargs, varkw
  554. def getargspec(func):
  555. """Get the names and default values of a function's arguments.
  556. A tuple of four things is returned: (args, varargs, varkw, defaults).
  557. 'args' is a list of the argument names (it may contain nested lists).
  558. 'varargs' and 'varkw' are the names of the * and ** arguments or None.
  559. 'defaults' is an n-tuple of the default values of the last n arguments.
  560. """
  561. if ismethod(func):
  562. func = func.im_func
  563. if not isfunction(func):
  564. raise TypeError('arg is not a Python function')
  565. args, varargs, varkw = getargs(func.func_code)
  566. return args, varargs, varkw, func.func_defaults
  567. def getargvalues(frame):
  568. """Get information about arguments passed into a particular frame.
  569. A tuple of four things is returned: (args, varargs, varkw, locals).
  570. 'args' is a list of the argument names (it may contain nested lists).
  571. 'varargs' and 'varkw' are the names of the * and ** arguments or None.
  572. 'locals' is the locals dictionary of the given frame."""
  573. args, varargs, varkw = getargs(frame.f_code)
  574. return args, varargs, varkw, frame.f_locals
  575. def joinseq(seq):
  576. if len(seq) == 1:
  577. return '(' + seq[0] + ',)'
  578. else:
  579. return '(' + string.join(seq, ', ') + ')'
  580. def strseq(object, convert, join=joinseq):
  581. """Recursively walk a sequence, stringifying each element."""
  582. if type(object) in [types.ListType, types.TupleType]:
  583. return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
  584. else:
  585. return convert(object)
  586. def formatargspec(args, varargs=None, varkw=None, defaults=None,
  587. formatarg=str,
  588. formatvarargs=lambda name: '*' + name,
  589. formatvarkw=lambda name: '**' + name,
  590. formatvalue=lambda value: '=' + repr(value),
  591. join=joinseq):
  592. """Format an argument spec from the 4 values returned by getargspec.
  593. The first four arguments are (args, varargs, varkw, defaults). The
  594. other four arguments are the corresponding optional formatting functions
  595. that are called to turn names and values into strings. The ninth
  596. argument is an optional function to format the sequence of arguments."""
  597. specs = []
  598. if defaults:
  599. firstdefault = len(args) - len(defaults)
  600. for i in range(len(args)):
  601. spec = strseq(args[i], formatarg, join)
  602. if defaults and i >= firstdefault:
  603. spec = spec + formatvalue(defaults[i - firstdefault])
  604. specs.append(spec)
  605. if varargs is not None:
  606. specs.append(formatvarargs(varargs))
  607. if varkw is not None:
  608. specs.append(formatvarkw(varkw))
  609. return '(' + string.join(specs, ', ') + ')'
  610. def formatargvalues(args, varargs, varkw, locals,
  611. formatarg=str,
  612. formatvarargs=lambda name: '*' + name,
  613. formatvarkw=lambda name: '**' + name,
  614. formatvalue=lambda value: '=' + repr(value),
  615. join=joinseq):
  616. """Format an argument spec from the 4 values returned by getargvalues.
  617. The first four arguments are (args, varargs, varkw, locals). The
  618. next four arguments are the corresponding optional formatting functions
  619. that are called to turn names and values into strings. The ninth
  620. argument is an optional function to format the sequence of arguments."""
  621. def convert(name, locals=locals,
  622. formatarg=formatarg, formatvalue=formatvalue):
  623. return formatarg(name) + formatvalue(locals[name])
  624. specs = []
  625. for i in range(len(args)):
  626. specs.append(strseq(args[i], convert, join))
  627. if varargs:
  628. specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
  629. if varkw:
  630. specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
  631. return '(' + string.join(specs, ', ') + ')'
  632. # -------------------------------------------------- stack frame extraction
  633. def getframeinfo(frame, context=1):
  634. """Get information about a frame or traceback object.
  635. A tuple of five things is returned: the filename, the line number of
  636. the current line, the function name, a list of lines of context from
  637. the source code, and the index of the current line within that list.
  638. The optional second argument specifies the number of lines of context
  639. to return, which are centered around the current line."""
  640. if istraceback(frame):
  641. frame = frame.tb_frame
  642. if not isframe(frame):
  643. raise TypeError('arg is not a frame or traceback object')
  644. filename = getsourcefile(frame) or getfile(frame)
  645. lineno = frame.f_lineno
  646. if context > 0:
  647. start = lineno - 1 - context//2
  648. try:
  649. lines, lnum = findsource(frame)
  650. except IOError:
  651. lines = index = None
  652. else:
  653. start = max(start, 1)
  654. start = min(start, len(lines) - context)
  655. lines = lines[start:start+context]
  656. index = lineno - 1 - start
  657. else:
  658. lines = index = None
  659. return (filename, lineno, frame.f_code.co_name, lines, index)
  660. def getlineno(frame):
  661. """Get the line number from a frame object, allowing for optimization."""
  662. # FrameType.f_lineno is now a descriptor that grovels co_lnotab
  663. return frame.f_lineno
  664. def getouterframes(frame, context=1):
  665. """Get a list of records for a frame and all higher (calling) frames.
  666. Each record contains a frame object, filename, line number, function
  667. name, a list of lines of context, and index within the context."""
  668. framelist = []
  669. while frame:
  670. framelist.append((frame,) + getframeinfo(frame, context))
  671. frame = frame.f_back
  672. return framelist
  673. def getinnerframes(tb, context=1):
  674. """Get a list of records for a traceback's frame and all lower frames.
  675. Each record contains a frame object, filename, line number, function
  676. name, a list of lines of context, and index within the context."""
  677. framelist = []
  678. while tb:
  679. framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
  680. tb = tb.tb_next
  681. return framelist
  682. currentframe = sys._getframe
  683. def stack(context=1):
  684. """Return a list of records for the stack above the caller's frame."""
  685. return getouterframes(sys._getframe(1), context)
  686. def trace(context=1):
  687. """Return a list of records for the stack below the current exception."""
  688. return getinnerframes(sys.exc_info()[2], context)