^Rc @sdZdZdZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z ddlmZd^\ZZZZd_\ZZZd`ZdZdZdZdZdZeedr dZn dZeedr1dZn dZdZ dZ!dZ"dZ#dZ$dZ%d Z&d!Z'd"Z(dd#Z*ed$d%Z+d&Z,d'Z-d(Z.d)Z/d*Z0d+Z1d,Z2ed-d.Z3d/Z4d0Z5d1Z6dd2Z7iZ8iZ9dd3Z:d4Z;d5Z<d6e=fd7YZ>d8dad9YZ?d:Z@d;ZAd<ZBd=ZCd>d?ZDed@dAZEdBZFedCdDZGdEZHedFdGZIdHZJdIZKeKdJZLdddeMdKdLdMeKdNZNeMdOdPdQeKdRZOdSZPedTdUZQddVZRdWZSddXZTddYZUeedZrejVZWn dd[ZWdd\ZXdd]ZYdS(bsGet useful information from live Python objects. This module encapsulates the interface provided by the internal special attributes (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(), getcallargs() - 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 sKa-Ping Yee s 1 Jan 2001iN(t attrgetter(t namedtupleiiiiii i@icCst|tjS(sReturn true if the object is a module. Module objects provide these attributes: __doc__ documentation string __file__ filename (missing for built-in modules)(t isinstancettypest ModuleType(tobject((s/usr/lib/python2.7/inspect.pytismodule3scCst|ttjfS(sReturn 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(RttypeRt ClassType(R((s/usr/lib/python2.7/inspect.pytisclass;scCst|tjS(sReturn 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(RRt MethodType(R((s/usr/lib/python2.7/inspect.pytismethodCs cCsDt|doCt|d oCt| oCt| oCt| S(sReturn 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().t__get__t__set__(thasattrR t isfunctionR (R((s/usr/lib/python2.7/inspect.pytismethoddescriptorNs   cCst|dot|dS(sReturn 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.R R (R(R((s/usr/lib/python2.7/inspect.pytisdatadescriptorbstMemberDescriptorTypecCst|tjS(sReturn true if the object is a member descriptor. Member descriptors are specialized descriptors defined in extension modules.(RRR(R((s/usr/lib/python2.7/inspect.pytismemberdescriptornscCstS(sReturn true if the object is a member descriptor. Member descriptors are specialized descriptors defined in extension modules.(tFalse(R((s/usr/lib/python2.7/inspect.pyRvstGetSetDescriptorTypecCst|tjS(sReturn true if the object is a getset descriptor. getset descriptors are specialized descriptors defined in extension modules.(RRR(R((s/usr/lib/python2.7/inspect.pytisgetsetdescriptorscCstS(sReturn true if the object is a getset descriptor. getset descriptors are specialized descriptors defined in extension modules.(R(R((s/usr/lib/python2.7/inspect.pyRscCst|tjS(sReturn 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__)(RRt FunctionType(R((s/usr/lib/python2.7/inspect.pyRs cCs,tt|st|o(|jjt@S(sReturn true if the object is a user-defined generator function. Generator function objects provides same attributes as functions. See help(isfunction) for attributes listing.(tboolRR t func_codetco_flagst CO_GENERATOR(R((s/usr/lib/python2.7/inspect.pytisgeneratorfunctionscCst|tjS(s 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(RRt GeneratorType(R((s/usr/lib/python2.7/inspect.pyt isgeneratorscCst|tjS(sbReturn 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)(RRt TracebackType(R((s/usr/lib/python2.7/inspect.pyt istracebackscCst|tjS(s|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(RRt FrameType(R((s/usr/lib/python2.7/inspect.pytisframescCst|tjS(suReturn 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(RRtCodeType(R((s/usr/lib/python2.7/inspect.pytiscodescCst|tjS(s,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(RRtBuiltinFunctionType(R((s/usr/lib/python2.7/inspect.pyt isbuiltinscCs.t|p-t|p-t|p-t|S(s<Return true if the object is any kind of function or method.(R&RR R(R((s/usr/lib/python2.7/inspect.pyt isroutines   cCs tt|to|jt@S(s:Return true if the object is an abstract base class (ABC).(RRRt __flags__tTPFLAGS_IS_ABSTRACT(R((s/usr/lib/python2.7/inspect.pyt isabstractscCs~g}xgt|D]Y}yt||}Wntk rBqnX| sV||r|j||fqqW|j|S(sReturn all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.(tdirtgetattrtAttributeErrortappendtsort(Rt predicatetresultstkeytvalue((s/usr/lib/python2.7/inspect.pyt getmemberss  t Attributesname kind defining_class objectc Csbt|}t|}g}x=|D]5}d}x\|f|D],}||jkr?|j|}|}Pq?q?Wt||}t|d|}t|trd}nt|trd}n~t|trd}nft |rd}nQt |rd}n<t||} t | s)t | r2d}nd}| }|j t ||||q%W|S(sReturn 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. t __objclass__s static methods class methodtpropertytmethodtdataN(tgetmroR+tNonet__dict__R,Rt staticmethodt classmethodR7RRR R.R5( tclstmrotnamestresulttnamethomeclstbasetobjtkindtobj_via_getattr((s/usr/lib/python2.7/inspect.pytclassify_class_attrss<               cCsB||krdS|j|x|jD]}t||q'WdS(N(R.t __bases__t _searchbases(R?taccumRE((s/usr/lib/python2.7/inspect.pyRKLs   cCs7t|dr|jSg}t||t|SdS(sHReturn tuple of base classes (including cls) in method resolution order.t__mro__N(RRMRKttuple(R?RB((s/usr/lib/python2.7/inspect.pyR:Ts  cCs,tj|}t|ttj|S(sBReturn the indent size, in spaces, at the start of a line of text.(tstringt expandtabstlentlstrip(tlinetexpline((s/usr/lib/python2.7/inspect.pyt indentsize^scCsBy |j}Wntk r!dSXt|tjs8dSt|S(sGet 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.N(t__doc__R-R;RRt StringTypestcleandoc(Rtdoc((s/usr/lib/python2.7/inspect.pytgetdoccs  cCsKytjtj|d}Wntk r3dSXtj}xO|dD]C}ttj|}|rHt||}t ||}qHqHW|r|dj|dsN(tostpathtbasenametmaptimpt get_suffixesR/Rs(Rwtfilenametsuffixestneglentsuffixtmodetmtype((s/usr/lib/python2.7/inspect.pyt getmoduleinfos  cCst|}|r|dSdS(s1Return the module name for a given file, or None.iN(R(RwRt((s/usr/lib/python2.7/inspect.pyt getmodulenames cCst|}tj|ddkr6|d d}nxMtjD]?\}}}d|krCtj|t| |krCdSqCWtjj |r|St t ||dr|S|t j kr|SdS( sReturn the filename that can be used to locate an object's source. Return None if no way can be identified to get the source. is.pycs.pyos.pytbt __loader__N(s.pycs.pyo(RrROtlowerRzR{RQR;RvRwtexistsRt getmodulet linecachetcache(RR|RRRG((s/usr/lib/python2.7/inspect.pyt getsourcefiles ,cCsC|dkr't|p!t|}ntjjtjj|S(sReturn 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.N(R;RRrRvRwtnormcasetabspath(Rt _filename((s/usr/lib/python2.7/inspect.pyt getabsfiles c Cst|r|St|dr2tjj|jS|dk r^|tkr^tjjt|Syt||}Wnt k rdSX|tkrtjjt|Sxtjj D]\}}t|rt|dr|j }|t j|dkrqn|t |W|| fStddS(sbReturn 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.iis<>ssource code not availablescould not get source codeis^(\s*)class\s*s\btcscould not find class definitiontco_firstlinenos"could not find function definitions+^(\s*def\s)|(.*(?Pntj tj ||}qWnx-|rtj|ddkrg|d*qdWx-|rtj|ddkrg|d)qWtj |dSndS( swGet lines of comments immediately preceding an object's source code. Returns None when source can't be found. iis#!itt#iN(RR( RRRiR;RRQROtstripR.RPRbRURR(RRcRtstarttcommentstendRftcomment((s/usr/lib/python2.7/inspect.pyt getcommentsIsJ  .&)  )  )   #""t EndOfBlockcBseZRS((RRm(((s/usr/lib/python2.7/inspect.pyRvst BlockFindercBs eZdZdZdZRS(s@Provide a tokeneater() method to detect the end of a code block.cCs1d|_t|_t|_t|_d|_dS(Nii(RfRtislambdatstartedtpasslinetlast(tself((s/usr/lib/python2.7/inspect.pyt__init__zs     c Cs8|\}}|\}} |js]|dkrQ|dkrEt|_nt|_nt|_n|tjkrt|_||_|jr4tq4n|jrn|tj kr|j d|_ t|_nj|tj kr|j d|_ |j dkr4tq4n0|j dkr4|tj tj fkr4tndS(Ntdeftclasstlambdaii(RRslambda(RtTrueRRttokenizetNEWLINERRRtINDENTRftDEDENTtCOMMENTtNL( RRttokent srow_scolt erow_ecolRStsrowtscolterowtecol((s/usr/lib/python2.7/inspect.pyt tokeneaters0               '(RRmRVRR(((s/usr/lib/python2.7/inspect.pyRxs cCsNt}y tjt|j|jWnttfk rBnX||j S(s@Extract the block of code at the top of the given list of lines.(RRtitertnextRRtIndentationErrorR(Rct blockfinder((s/usr/lib/python2.7/inspect.pytgetblocks   cCsDt|\}}t|r(|dfSt|||dfSdS(sReturn 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.iiN(RRR(RRcR((s/usr/lib/python2.7/inspect.pytgetsourceliness cCs"t|\}}tj|dS(sReturn 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.R(RRORb(RRcR((s/usr/lib/python2.7/inspect.pyt getsourcescCsvg}|jdtddxP|D]H}|j||jf||kr&|jt||||q&q&W|S(s-Recursive helper function for getclasstree().R2RmR(R/RR.RJtwalktree(tclassestchildrentparentR1R((s/usr/lib/python2.7/inspect.pyRs  $icCsi}g}x|D]}|jryxp|jD]F}||krKg||t|dkr"d|ddSdtj|ddSdS(Nit(is,)s, t)(RQRORb(tseq((s/usr/lib/python2.7/inspect.pytjoinseq?scCsBt|ttfkr4|t||d|S||SdS(s7Recursively walk a sequence, stringifying each element.cSst|||S(N(tstrseq(toRtj((s/usr/lib/python2.7/inspect.pyRuHsN(RRRNRy(RtconvertRb((s/usr/lib/python2.7/inspect.pyREscCsd|S(Nt*((RC((s/usr/lib/python2.7/inspect.pyRuNscCsd|S(Ns**((RC((s/usr/lib/python2.7/inspect.pyRuOscCsdt|S(Nt=(trepr(R3((s/usr/lib/python2.7/inspect.pyRuPsc Csg} |r%t|t|} nxft|D]X\} } t| ||} |r}| | kr}| ||| | } n| j| q2W|dk r| j||n|dk r| j||ndtj| ddS(sgFormat 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.Rs, RN(RQt enumerateRR.R;RORb(RRRtdefaultst formatargt formatvarargst formatvarkwt formatvalueRbtspecst firstdefaultRgtargtspec((s/usr/lib/python2.7/inspect.pyt formatargspecLs   cCsd|S(NR((RC((s/usr/lib/python2.7/inspect.pyRuhscCsd|S(Ns**((RC((s/usr/lib/python2.7/inspect.pyRuiscCsdt|S(NR(R (R3((s/usr/lib/python2.7/inspect.pyRujsc Cs|||d} g} x7tt|D]#} | jt|| | |q+W|r|| j|||||n|r| j|||||ndtj| ddS(sfFormat 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.cSs|||||S(N((RCtlocalsR R((s/usr/lib/python2.7/inspect.pyRrsRs, R(R`RQR.RRORb( RRRRR R RRRbRRRg((s/usr/lib/python2.7/inspect.pytformatargvaluesfs !$$c st|\}}}}|j}igfdfd}t|r|jdk r|jf|}nt|} | t|} t|} |rt|nd} x*t||D]\} }| |qW|r*| | kr||| |  q|dnd| koA| knrtd||r[dnd| | dkrsdnd | fnS| dkr| r|r| rtd || fqqtd || fnxg|D]_} t| t r| |kr|| r&td || fq?| |j | qqW|rxAt|| |D](\} }|| s^| |q^q^Wn|r||n[|rt t |}t|t r|jtjd }ntd||fn| tg|D]} || r | ^q }|r}| | }td||rRdnd||dkrjdnd | fnS(sGet the mapping of arguments to values. A dict is returned, with keys the function argument names (including the names of the * and ** arguments, if any), and values the respective bound values from 'positional' and 'named'.cst|tr||RARDREt currentframeRRH(((s/usr/lib/python2.7/inspect.pyts                        E         . C -)  :       [ !