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