# -*- coding: iso-8859-1 -*-"""Get useful information from live Python objects.This module encapsulates the interface provided by the internal specialattributes (func_*, co_*, im_*, tb_*, etc.) in a friendlier fashion.It also provides some help for examining source code and class layout.Here are some of the useful functions provided by this module: ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(), isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(), isroutine() - check object types getmembers() - get members of an object that satisfy a given condition getfile(), getsourcefile(), getsource() - find an object's source code getdoc(), getcomments() - get documentation on an object getmodule() - determine the module that an object came from getclasstree() - arrange classes so as to represent their hierarchy getargspec(), getargvalues() - get info about function arguments formatargspec(), formatargvalues() - format an argument spec getouterframes(), getinnerframes() - get info about frames currentframe() - get the current stack frame stack(), trace() - get info about frames on the stack or in a traceback"""# This module is in the public domain. No warranties.__author__='Ka-Ping Yee <ping@lfw.org>'__date__='1 Jan 2001'importsysimportosimporttypesimportstringimportreimportdisimportimpimporttokenizeimportlinecachefromoperatorimportattrgetterfromcollectionsimportnamedtuple# These constants are from Include/code.h.CO_OPTIMIZED,CO_NEWLOCALS,CO_VARARGS,CO_VARKEYWORDS=0x1,0x2,0x4,0x8CO_NESTED,CO_GENERATOR,CO_NOFREE=0x10,0x20,0x40# See Include/object.hTPFLAGS_IS_ABSTRACT=1<<20# ----------------------------------------------------------- type-checkingdefismodule(object):"""Return true if the object is a module. Module objects provide these attributes: __doc__ documentation string __file__ filename (missing for built-in modules)"""returnisinstance(object,types.ModuleType)defisclass(object):"""Return true if the object is a class. Class objects provide these attributes: __doc__ documentation string __module__ name of module in which this class was defined"""returnisinstance(object,types.ClassType)orhasattr(object,'__bases__')defismethod(object):"""Return true if the object is an instance method. Instance method objects provide these attributes: __doc__ documentation string __name__ name with which this method was defined im_class class object in which this method belongs im_func function object containing implementation of method im_self instance to which this method is bound, or None"""returnisinstance(object,types.MethodType)defismethoddescriptor(object):"""Return true if the object is a method descriptor. But not if ismethod() or isclass() or isfunction() are true. This is new in Python 2.2, and, for example, is true of int.__add__. An object passing this test has a __get__ attribute but not a __set__ attribute, but beyond that the set of attributes varies. __name__ is usually sensible, and __doc__ often is. Methods implemented via descriptors that also pass one of the other tests return false from the ismethoddescriptor() test, simply because the other tests promise more -- you can, e.g., count on having the im_func attribute (etc) when an object passes ismethod()."""return(hasattr(object,"__get__")andnothasattr(object,"__set__")# else it's a data descriptorandnotismethod(object)# mutual exclusionandnotisfunction(object)andnotisclass(object))defisdatadescriptor(object):"""Return true if the object is a data descriptor. Data descriptors have both a __get__ and a __set__ attribute. Examples are properties (defined in Python) and getsets and members (defined in C). Typically, data descriptors will also have __name__ and __doc__ attributes (properties, getsets, and members have both of these attributes), but this is not guaranteed."""return(hasattr(object,"__set__")andhasattr(object,"__get__"))ifhasattr(types,'MemberDescriptorType'):# CPython and equivalentdefismemberdescriptor(object):"""Return true if the object is a member descriptor. Member descriptors are specialized descriptors defined in extension modules."""returnisinstance(object,types.MemberDescriptorType)else:# Other implementationsdefismemberdescriptor(object):"""Return true if the object is a member descriptor. Member descriptors are specialized descriptors defined in extension modules."""returnFalseifhasattr(types,'GetSetDescriptorType'):# CPython and equivalentdefisgetsetdescriptor(object):"""Return true if the object is a getset descriptor. getset descriptors are specialized descriptors defined in extension modules."""returnisinstance(object,types.GetSetDescriptorType)else:# Other implementationsdefisgetsetdescriptor(object):"""Return true if the object is a getset descriptor. getset descriptors are specialized descriptors defined in extension modules."""returnFalsedefisfunction(object):"""Return true if the object is a user-defined function. Function objects provide these attributes: __doc__ documentation string __name__ name with which this function was defined func_code code object containing compiled function bytecode func_defaults tuple of any default values for arguments func_doc (same as __doc__) func_globals global namespace in which this function was defined func_name (same as __name__)"""returnisinstance(object,types.FunctionType)defisgeneratorfunction(object):"""Return true if the object is a user-defined generator function. Generator function objects provides same attributes as functions. See isfunction.__doc__ for attributes listing."""if(isfunction(object)orismethod(object))and \
object.func_code.co_flags&CO_GENERATOR:returnTruedefisgenerator(object):"""Return true if the object is a generator. Generator objects provide these attributes: __iter__ defined to support interation over container close raises a new GeneratorExit exception inside the generator to terminate the iteration gi_code code object gi_frame frame object or possibly None once the generator has been exhausted gi_running set to 1 when generator is executing, 0 otherwise next return the next item from the container send resumes the generator and "sends" a value that becomes the result of the current yield-expression throw used to raise an exception inside the generator"""returnisinstance(object,types.GeneratorType)defistraceback(object):"""Return true if the object is a traceback. Traceback objects provide these attributes: tb_frame frame object at this level tb_lasti index of last attempted instruction in bytecode tb_lineno current line number in Python source code tb_next next inner traceback object (called by this level)"""returnisinstance(object,types.TracebackType)defisframe(object):"""Return true if the object is a frame object. Frame objects provide these attributes: f_back next outer frame object (this frame's caller) f_builtins built-in namespace seen by this frame f_code code object being executed in this frame f_exc_traceback traceback if raised in this frame, or None f_exc_type exception type if raised in this frame, or None f_exc_value exception value if raised in this frame, or None f_globals global namespace seen by this frame f_lasti index of last attempted instruction in bytecode f_lineno current line number in Python source code f_locals local namespace seen by this frame f_restricted 0 or 1 if frame is in restricted execution mode f_trace tracing function for this frame, or None"""returnisinstance(object,types.FrameType)defiscode(object):"""Return true if the object is a code object. Code objects provide these attributes: co_argcount number of arguments (not including * or ** args) co_code string of raw compiled bytecode co_consts tuple of constants used in the bytecode co_filename name of file in which this code object was created co_firstlineno number of first line in Python source code co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg co_lnotab encoded mapping of line numbers to bytecode indices co_name name with which this code object was defined co_names tuple of names of local variables co_nlocals number of local variables co_stacksize virtual machine stack space required co_varnames tuple of names of arguments and local variables"""returnisinstance(object,types.CodeType)defisbuiltin(object):"""Return true if the object is a built-in function or method. Built-in functions and methods provide these attributes: __doc__ documentation string __name__ original name of this function or method __self__ instance to which a method is bound, or None"""returnisinstance(object,types.BuiltinFunctionType)defisroutine(object):"""Return true if the object is any kind of function or method."""return(isbuiltin(object)orisfunction(object)orismethod(object)orismethoddescriptor(object))defisgenerator(object):"""Return true if the object is a generator object."""returnisinstance(object,types.GeneratorType)defisabstract(object):"""Return true if the object is an abstract base class (ABC)."""returnisinstance(object,type)andobject.__flags__&TPFLAGS_IS_ABSTRACTdefgetmembers(object,predicate=None):"""Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate."""results=[]forkeyindir(object):value=getattr(object,key)ifnotpredicateorpredicate(value):results.append((key,value))results.sort()returnresultsAttribute=namedtuple('Attribute','name kind defining_class object')defclassify_class_attrs(cls):"""Return list of attribute-descriptor tuples. For each name in dir(cls), the return list contains a 4-tuple with these elements: 0. The name (a string). 1. The kind of attribute this is, one of these strings: 'class method' created via classmethod() 'static method' created via staticmethod() 'property' created via property() 'method' any other flavor of method 'data' not a method 2. The class which defined this attribute (a class). 3. The object as obtained directly from the defining class's __dict__, not via getattr. This is especially important for data attributes: C.data is just a data object, but C.__dict__['data'] may be a data descriptor with additional info, like a __doc__ string. """mro=getmro(cls)names=dir(cls)result=[]fornameinnames:# Get the object associated with the name.# Getting an obj from the __dict__ sometimes reveals more than# using getattr. Static and class methods are dramatic examples.ifnameincls.__dict__:obj=cls.__dict__[name]else:obj=getattr(cls,name)# Figure out where it was defined.homecls=getattr(obj,"__objclass__",None)ifhomeclsisNone:# search the dicts.forbaseinmro:ifnameinbase.__dict__:homecls=basebreak# Get the object again, in order to get it from the defining# __dict__ instead of via getattr (if possible).ifhomeclsisnotNoneandnameinhomecls.__dict__:obj=homecls.__dict__[name]# Also get the object via getattr.obj_via_getattr=getattr(cls,name)# Classify the object.ifisinstance(obj,staticmethod):kind="static method"elifisinstance(obj,classmethod):kind="class method"elifisinstance(obj,property):kind="property"elif(ismethod(obj_via_getattr)orismethoddescriptor(obj_via_getattr)):kind="method"else:kind="data"result.append(Attribute(name,kind,homecls,obj))returnresult# ----------------------------------------------------------- class helpersdef_searchbases(cls,accum):# Simulate the "classic class" search order.ifclsinaccum:returnaccum.append(cls)forbaseincls.__bases__:_searchbases(base,accum)defgetmro(cls):"Return tuple of base classes (including cls) in method resolution order."ifhasattr(cls,"__mro__"):returncls.__mro__else:result=[]_searchbases(cls,result)returntuple(result)# -------------------------------------------------- source code extractiondefindentsize(line):"""Return the indent size, in spaces, at the start of a line of text."""expline=string.expandtabs(line)returnlen(expline)-len(string.lstrip(expline))defgetdoc(object):"""Get the documentation string for an object. All tabs are expanded to spaces. To clean up docstrings that are indented to line up with blocks of code, any whitespace than can be uniformly removed from the second line onwards is removed."""try:doc=object.__doc__exceptAttributeError:returnNoneifnotisinstance(doc,types.StringTypes):returnNonereturncleandoc(doc)defcleandoc(doc):"""Clean up indentation from docstrings. Any whitespace that can be uniformly removed from the second line onwards is removed."""try:lines=string.split(string.expandtabs(doc),'\n')exceptUnicodeError:returnNoneelse:# Find minimum indentation of any non-blank lines after first line.margin=sys.maxintforlineinlines[1:]:content=len(string.lstrip(line))ifcontent:indent=len(line)-contentmargin=min(margin,indent)# Remove indentation.iflines:lines[0]=lines[0].lstrip()ifmargin<sys.maxint:foriinrange(1,len(lines)):lines[i]=lines[i][margin:]# Remove any trailing or leading blank lines.whilelinesandnotlines[-1]:lines.pop()whilelinesandnotlines[0]:lines.pop(0)returnstring.join(lines,'\n')defgetfile(object):"""Work out which source or compiled file an object was defined in."""ifismodule(object):ifhasattr(object,'__file__'):returnobject.__file__raiseTypeError('arg is a built-in module')ifisclass(object):object=sys.modules.get(object.__module__)ifhasattr(object,'__file__'):returnobject.__file__raiseTypeError('arg is a built-in class')ifismethod(object):object=object.im_funcifisfunction(object):object=object.func_codeifistraceback(object):object=object.tb_frameifisframe(object):object=object.f_codeifiscode(object):returnobject.co_filenameraiseTypeError('arg is not a module, class, method, ''function, traceback, frame, or code object')ModuleInfo=namedtuple('ModuleInfo','name suffix mode module_type')defgetmoduleinfo(path):"""Get the module name, suffix, mode, and module type for a given file."""filename=os.path.basename(path)suffixes=map(lambdainfo:(-len(info[0]),info[0],info[1],info[2]),imp.get_suffixes())suffixes.sort()# try longest suffixes first, in case they overlapforneglen,suffix,mode,mtypeinsuffixes:iffilename[neglen:]==suffix:returnModuleInfo(filename[:neglen],suffix,mode,mtype)defgetmodulename(path):"""Return the module name for a given file, or None."""info=getmoduleinfo(path)ifinfo:returninfo[0]defgetsourcefile(object):"""Return the Python source file an object was defined in, if it exists."""filename=getfile(object)ifstring.lower(filename[-4:])in('.pyc','.pyo'):filename=filename[:-4]+'.py'forsuffix,mode,kindinimp.get_suffixes():if'b'inmodeandstring.lower(filename[-len(suffix):])==suffix:# Looks like a binary file. We want to only return a text file.returnNoneifos.path.exists(filename):returnfilename# only return a non-existent filename if the module has a PEP 302 loaderifhasattr(getmodule(object,filename),'__loader__'):returnfilenamedefgetabsfile(object,_filename=None):"""Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routine normalizes the result as much as possible."""if_filenameisNone:_filename=getsourcefile(object)orgetfile(object)returnos.path.normcase(os.path.abspath(_filename))modulesbyfile={}_filesbymodname={}defgetmodule(object,_filename=None):"""Return the module an object was defined in, or None if not found."""ifismodule(object):returnobjectifhasattr(object,'__module__'):returnsys.modules.get(object.__module__)# Try the filename to modulename cacheif_filenameisnotNoneand_filenameinmodulesbyfile:returnsys.modules.get(modulesbyfile[_filename])# Try the cache again with the absolute file nametry:file=getabsfile(object,_filename)exceptTypeError:returnNoneiffileinmodulesbyfile:returnsys.modules.get(modulesbyfile[file])# Update the filename to module name cache and check yet again# Copy sys.modules in order to cope with changes while iteratingformodname,moduleinsys.modules.items():ifismodule(module)andhasattr(module,'__file__'):f=module.__file__iff==_filesbymodname.get(modname,None):# Have already mapped this module, so skip itcontinue_filesbymodname[modname]=ff=getabsfile(module)# Always map to the name the module knows itself bymodulesbyfile[f]=modulesbyfile[os.path.realpath(f)]=module.__name__iffileinmodulesbyfile:returnsys.modules.get(modulesbyfile[file])# Check the main modulemain=sys.modules['__main__']ifnothasattr(object,'__name__'):returnNoneifhasattr(main,object.__name__):mainobject=getattr(main,object.__name__)ifmainobjectisobject:returnmain# Check builtinsbuiltin=sys.modules['__builtin__']ifhasattr(builtin,object.__name__):builtinobject=getattr(builtin,object.__name__)ifbuiltinobjectisobject:returnbuiltindeffindsource(object):"""Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved."""file=getsourcefile(object)orgetfile(object)module=getmodule(object,file)ifmodule:lines=linecache.getlines(file,module.__dict__)else:lines=linecache.getlines(file)ifnotlines:raiseIOError('could not get source code')ifismodule(object):returnlines,0ifisclass(object):name=object.__name__pat=re.compile(r'^(\s*)class\s*'+name+r'\b')# make some effort to find the best matching class definition:# use the one with the least indentation, which is the one# that's most probably not inside a function definition.candidates=[]foriinrange(len(lines)):match=pat.match(lines[i])ifmatch:# if it's at toplevel, it's already the best oneiflines[i][0]=='c':returnlines,i# else add whitespace to candidate listcandidates.append((match.group(1),i))ifcandidates:# this will sort by whitespace, and by line number,# less whitespace firstcandidates.sort()returnlines,candidates[0][1]else:raiseIOError('could not find class definition')ifismethod(object):object=object.im_funcifisfunction(object):object=object.func_codeifistraceback(object):object=object.tb_frameifisframe(object):object=object.f_codeifiscode(object):ifnothasattr(object,'co_firstlineno'):raiseIOError('could not find function definition')lnum=object.co_firstlineno-1pat=re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')whilelnum>0:ifpat.match(lines[lnum]):breaklnum=lnum-1returnlines,lnumraiseIOError('could not find code object')defgetcomments(object):"""Get lines of comments immediately preceding an object's source code. Returns None when source can't be found. """try:lines,lnum=findsource(object)except(IOError,TypeError):returnNoneifismodule(object):# Look for a comment block at the top of the file.start=0iflinesandlines[0][:2]=='#!':start=1whilestart<len(lines)andstring.strip(lines[start])in('','#'):start=start+1ifstart<len(lines)andlines[start][:1]=='#':comments=[]end=startwhileend<len(lines)andlines[end][:1]=='#':comments.append(string.expandtabs(lines[end]))end=end+1returnstring.join(comments,'')# Look for a preceding block of comments at the same indentation.eliflnum>0:indent=indentsize(lines[lnum])end=lnum-1ifend>=0andstring.lstrip(lines[end])[:1]=='#'and \
indentsize(lines[end])==indent:comments=[string.lstrip(string.expandtabs(lines[end]))]ifend>0:end=end-1comment=string.lstrip(string.expandtabs(lines[end]))whilecomment[:1]=='#'andindentsize(lines[end])==indent:comments[:0]=[comment]end=end-1ifend<0:breakcomment=string.lstrip(string.expandtabs(lines[end]))whilecommentsandstring.strip(comments[0])=='#':comments[:1]=[]whilecommentsandstring.strip(comments[-1])=='#':comments[-1:]=[]returnstring.join(comments,'')classEndOfBlock(Exception):passclassBlockFinder:"""Provide a tokeneater() method to detect the end of a code block."""def__init__(self):self.indent=0self.islambda=Falseself.started=Falseself.passline=Falseself.last=1deftokeneater(self,type,token,srow_scol,erow_ecol,line):srow,scol=srow_scolerow,ecol=erow_ecolifnotself.started:# look for the first "def", "class" or "lambda"iftokenin("def","class","lambda"):iftoken=="lambda":self.islambda=Trueself.started=Trueself.passline=True# skip to the end of the lineeliftype==tokenize.NEWLINE:self.passline=False# stop skipping when a NEWLINE is seenself.last=srowifself.islambda:# lambdas always end at the first NEWLINEraiseEndOfBlockelifself.passline:passeliftype==tokenize.INDENT:self.indent=self.indent+1self.passline=Trueeliftype==tokenize.DEDENT:self.indent=self.indent-1# the end of matching indent/dedent pairs end a block# (note that this only works for "def"/"class" blocks,# not e.g. for "if: else:" or "try: finally:" blocks)ifself.indent<=0:raiseEndOfBlockelifself.indent==0andtypenotin(tokenize.COMMENT,tokenize.NL):# any other token on the same indentation level end the previous# block as well, except the pseudo-tokens COMMENT and NL.raiseEndOfBlockdefgetblock(lines):"""Extract the block of code at the top of the given list of lines."""blockfinder=BlockFinder()try:tokenize.tokenize(iter(lines).next,blockfinder.tokeneater)except(EndOfBlock,IndentationError):passreturnlines[:blockfinder.last]defgetsourcelines(object):"""Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An IOError is raised if the source code cannot be retrieved."""lines,lnum=findsource(object)ifismodule(object):returnlines,0else:returngetblock(lines[lnum:]),lnum+1defgetsource(object):"""Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An IOError is raised if the source code cannot be retrieved."""lines,lnum=getsourcelines(object)returnstring.join(lines,'')# --------------------------------------------------- class tree extractiondefwalktree(classes,children,parent):"""Recursive helper function for getclasstree()."""results=[]classes.sort(key=attrgetter('__module__','__name__'))forcinclasses:results.append((c,c.__bases__))ifcinchildren:results.append(walktree(children[c],children,c))returnresultsdefgetclasstree(classes,unique=0):"""Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. Each entry is a 2-tuple containing a class and a tuple of its base classes. If the 'unique' argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times."""children={}roots=[]forcinclasses:ifc.__bases__:forparentinc.__bases__:ifnotparentinchildren:children[parent]=[]children[parent].append(c)ifuniqueandparentinclasses:breakelifcnotinroots:roots.append(c)forparentinchildren:ifparentnotinclasses:roots.append(parent)returnwalktree(roots,children,None)# ------------------------------------------------ argument list extractionArguments=namedtuple('Arguments','args varargs keywords')defgetargs(co):"""Get information about the arguments accepted by a code object. Three things are returned: (args, varargs, varkw), where 'args' is a list of argument names (possibly containing nested lists), and 'varargs' and 'varkw' are the names of the * and ** arguments or None."""ifnotiscode(co):raiseTypeError('arg is not a code object')nargs=co.co_argcountnames=co.co_varnamesargs=list(names[:nargs])step=0# The following acrobatics are for anonymous (tuple) arguments.foriinrange(nargs):ifargs[i][:1]in('','.'):stack,remain,count=[],[],[]whilestep<len(co.co_code):op=ord(co.co_code[step])step=step+1ifop>=dis.HAVE_ARGUMENT:opname=dis.opname[op]value=ord(co.co_code[step])+ord(co.co_code[step+1])*256step=step+2ifopnamein('UNPACK_TUPLE','UNPACK_SEQUENCE'):remain.append(value)count.append(value)elifopname=='STORE_FAST':stack.append(names[value])# Special case for sublists of length 1: def foo((bar))# doesn't generate the UNPACK_TUPLE bytecode, so if# `remain` is empty here, we have such a sublist.ifnotremain:stack[0]=[stack[0]]breakelse:remain[-1]=remain[-1]-1whileremain[-1]==0:remain.pop()size=count.pop()stack[-size:]=[stack[-size:]]ifnotremain:breakremain[-1]=remain[-1]-1ifnotremain:breakargs[i]=stack[0]varargs=Noneifco.co_flags&CO_VARARGS:varargs=co.co_varnames[nargs]nargs=nargs+1varkw=Noneifco.co_flags&CO_VARKEYWORDS:varkw=co.co_varnames[nargs]returnArguments(args,varargs,varkw)ArgSpec=namedtuple('ArgSpec','args varargs keywords defaults')defgetargspec(func):"""Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. """ifismethod(func):func=func.im_funcifnotisfunction(func):raiseTypeError('arg is not a Python function')args,varargs,varkw=getargs(func.func_code)returnArgSpec(args,varargs,varkw,func.func_defaults)ArgInfo=namedtuple('ArgInfo','args varargs keywords locals')defgetargvalues(frame):"""Get information about arguments passed into a particular frame. A tuple of four things is returned: (args, varargs, varkw, locals). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'locals' is the locals dictionary of the given frame."""args,varargs,varkw=getargs(frame.f_code)returnargs,varargs,varkw,frame.f_localsdefjoinseq(seq):iflen(seq)==1:return'('+seq[0]+',)'else:return'('+string.join(seq,', ')+')'defstrseq(object,convert,join=joinseq):"""Recursively walk a sequence, stringifying each element."""iftype(object)in(list,tuple):returnjoin(map(lambdao,c=convert,j=join:strseq(o,c,j),object))else:returnconvert(object)defformatargspec(args,varargs=None,varkw=None,defaults=None,formatarg=str,formatvarargs=lambdaname:'*'+name,formatvarkw=lambdaname:'**'+name,formatvalue=lambdavalue:'='+repr(value),join=joinseq):"""Format an argument spec from the 4 values returned by getargspec. The first four arguments are (args, varargs, varkw, defaults). The other four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional function to format the sequence of arguments."""specs=[]ifdefaults:firstdefault=len(args)-len(defaults)foriinrange(len(args)):spec=strseq(args[i],formatarg,join)ifdefaultsandi>=firstdefault:spec=spec+formatvalue(defaults[i-firstdefault])specs.append(spec)ifvarargsisnotNone:specs.append(formatvarargs(varargs))ifvarkwisnotNone:specs.append(formatvarkw(varkw))return'('+string.join(specs,', ')+')'defformatargvalues(args,varargs,varkw,locals,formatarg=str,formatvarargs=lambdaname:'*'+name,formatvarkw=lambdaname:'**'+name,formatvalue=lambdavalue:'='+repr(value),join=joinseq):"""Format an argument spec from the 4 values returned by getargvalues. The first four arguments are (args, varargs, varkw, locals). The next four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional function to format the sequence of arguments."""defconvert(name,locals=locals,formatarg=formatarg,formatvalue=formatvalue):returnformatarg(name)+formatvalue(locals[name])specs=[]foriinrange(len(args)):specs.append(strseq(args[i],convert,join))ifvarargs:specs.append(formatvarargs(varargs)+formatvalue(locals[varargs]))ifvarkw:specs.append(formatvarkw(varkw)+formatvalue(locals[varkw]))return'('+string.join(specs,', ')+')'# -------------------------------------------------- stack frame extractionTraceback=namedtuple('Traceback','filename lineno function code_context index')defgetframeinfo(frame,context=1):"""Get information about a frame or traceback object. A tuple of five things is returned: the filename, the line number of the current line, the function name, a list of lines of context from the source code, and the index of the current line within that list. The optional second argument specifies the number of lines of context to return, which are centered around the current line."""ifistraceback(frame):lineno=frame.tb_linenoframe=frame.tb_frameelse:lineno=frame.f_linenoifnotisframe(frame):raiseTypeError('arg is not a frame or traceback object')filename=getsourcefile(frame)orgetfile(frame)ifcontext>0:start=lineno-1-context//2try:lines,lnum=findsource(frame)exceptIOError:lines=index=Noneelse:start=max(start,1)start=max(0,min(start,len(lines)-context))lines=lines[start:start+context]index=lineno-1-startelse:lines=index=NonereturnTraceback(filename,lineno,frame.f_code.co_name,lines,index)defgetlineno(frame):"""Get the line number from a frame object, allowing for optimization."""# FrameType.f_lineno is now a descriptor that grovels co_lnotabreturnframe.f_linenodefgetouterframes(frame,context=1):"""Get a list of records for a frame and all higher (calling) frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context."""framelist=[]whileframe:framelist.append((frame,)+getframeinfo(frame,context))frame=frame.f_backreturnframelistdefgetinnerframes(tb,context=1):"""Get a list of records for a traceback's frame and all lower frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context."""framelist=[]whiletb:framelist.append((tb.tb_frame,)+getframeinfo(tb,context))tb=tb.tb_nextreturnframelistcurrentframe=sys._getframedefstack(context=1):"""Return a list of records for the stack above the caller's frame."""returngetouterframes(sys._getframe(1),context)deftrace(context=1):"""Return a list of records for the stack below the current exception."""returngetinnerframes(sys.exc_info()[2],context)