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