PK•Tî6“×2EGG-INFO/dependency_links.txt PK•Tî67SäBEGG-INFO/namespace_packages.txtpeak peak.util PK•Tî6ŒMû û EGG-INFO/PKG-INFOMetadata-Version: 1.0 Name: DecoratorTools Version: 1.5 Summary: Use class and function decorators -- even in Python 2.3 (now with source debugging for generated code)! Home-page: http://cheeseshop.python.org/pypi/DecoratorTools Author: Phillip J. Eby Author-email: peak@eby-sarna.com License: PSF or ZPL Description: Want to use decorators, but still need to support Python 2.3? Wish you could have class decorators, decorate arbitrary assignments, or match decorated function signatures to their original functions? Then you need "DecoratorTools". Some quick examples:: # Method decorator example from peak.util.decorators import decorate class Demo1(object): decorate(classmethod) # equivalent to @classmethod def example(cls): print "hello from", cls # Class decorator example from peak.util.decorators import decorate_class def my_class_decorator(): def decorator(cls): print "decorating", cls return cls decorate_class(decorator) class Demo2: my_class_decorator() # "decorating " will be printed when execution gets here Installing DecoratorTools (using ``"easy_install DecoratorTools"`` or ``"setup.py install"``) gives you access to the ``peak.util.decorators`` module. The tools in this module have been bundled for years inside of PEAK, PyProtocols, RuleDispatch, and the zope.interface package, so they have been widely used and tested. (Unit tests are also included, of course.) This standalone version is backward-compatible with the bundled versions, so you can mix and match decorators from this package with those provided by zope.interface, TurboGears, etc. For complete documentation, see the `DecoratorTools manual`_. Changes since version 1.4: * Added ``enclosing_frame()`` function, so that complex decorators that call DecoratorTools functions while being called *by* DecoratorTools functions, will work correctly. Changes since version 1.3: * Added support for debugging generated code, including the code generated by ``rewrap()`` and ``template_function``. Changes since version 1.2: * Added ``rewrap()`` function and ``template_function`` decorator to support signature matching for decorated functions. (These features are similar to the ones provided by Michele Simionato's "decorator" package, but do not require Python 2.4 and don't change the standard idioms for creating decorator functions.) * ``decorate_class()`` will no longer apply duplicate class decorator callbacks unless the ``allow_duplicates`` argument is true. Changes since version 1.1: * Fixed a problem where instances of different struct types could equal each other Changes since version 1.0: * The ``struct()`` decorator makes it easy to create tuple-like data structure types, by decorating a constructor function. .. _DecoratorTools Manual: http://peak.telecommunity.com/DevCenter/DecoratorTools#toc .. _toc: Platform: UNKNOWN PK•Tî6 s+ˆnnEGG-INFO/SOURCES.txtREADME.txt setup.cfg setup.py test_decorators.py DecoratorTools.egg-info/PKG-INFO DecoratorTools.egg-info/SOURCES.txt DecoratorTools.egg-info/dependency_links.txt DecoratorTools.egg-info/namespace_packages.txt DecoratorTools.egg-info/top_level.txt ez_setup/README.txt ez_setup/__init__.py peak/__init__.py peak/util/__init__.py peak/util/decorators.py PK•Tî6†êÁEGG-INFO/top_level.txtpeak PK•Tî6“×2EGG-INFO/zip-safe PK/ ·4‰kÔ<99peak/__init__.py__import__('pkg_resources').declare_namespace(__name__) PK•Tî6ºÑgéÍÍpeak/__init__.pyc;ò ™rDc@sedƒieƒdS(s pkg_resourcesN(s __import__sdeclare_namespaces__name__(((s&build\bdist.win32\egg\peak\__init__.pys?sPK•Tî6ºÑgéÍÍpeak/__init__.pyo;ò ™rDc@sedƒieƒdS(s pkg_resourcesN(s __import__sdeclare_namespaces__name__(((s&build\bdist.win32\egg\peak\__init__.pys?sPK Tî6&ÃÓFÓFpeak/util/decorators.pyfrom types import ClassType, FunctionType import sys, os __all__ = [ 'decorate_class', 'metaclass_is_decorator', 'metaclass_for_bases', 'frameinfo', 'decorate_assignment', 'decorate', 'struct', 'template_function', 'rewrap', 'cache_source', 'enclosing_frame', ] def decorate(*decorators): """Use Python 2.4 decorators w/Python 2.3+ Example:: class Foo(object): decorate(classmethod) def something(cls,etc): \"""This is a classmethod\""" You can pass in more than one decorator, and they are applied in the same order that would be used for ``@`` decorators in Python 2.4. This function can be used to write decorator-using code that will work with both Python 2.3 and 2.4 (and up). """ if len(decorators)>1: decorators = list(decorators) decorators.reverse() def callback(frame,k,v,old_locals): for d in decorators: v = d(v) return v return decorate_assignment(callback) def enclosing_frame(frame=None, level=3): """Get an enclosing frame that skips DecoratorTools callback code""" frame = frame or sys._getframe(level) while frame.f_globals.get('__name__')==__name__: frame = frame.f_back return frame def name_and_spec(func): from inspect import formatargspec, getargspec funcname = func.__name__ if funcname=='': funcname = "anonymous" args, varargs, kwargs, defaults = getargspec(func) return funcname, formatargspec(args, varargs, kwargs)[1:-1] def qname(func): m = func.__module__ return m and m+'.'+func.__name__ or func.__name__ def apply_template(wrapper, func, *args, **kw): funcname, argspec = name_and_spec(func) wrapname, wrapspec = name_and_spec(wrapper) body = wrapper.__doc__.replace('%','%%').replace('$args','%(argspec)s') d ={} body = """ def %(wrapname)s(%(wrapspec)s): def %(funcname)s(%(argspec)s): """+body+""" return %(funcname)s """ body %= locals() filename = "<%s wrapping %s at 0x%08X>" % (qname(wrapper), qname(func), id(func)) exec compile(body, filename, "exec") in func.func_globals, d f = d[wrapname](func, *args, **kw) cache_source(filename, body, f) f.func_defaults = func.func_defaults f.__doc__ = func.__doc__ f.__dict__ = func.__dict__ return f def rewrap(func, wrapper): """Create a wrapper with the signature of `func` and a body of `wrapper` Example:: def before_and_after(func): def decorated(*args, **kw): print "before" try: return func(*args, **kw) finally: print "after" return rewrap(func, decorated) The above function is a normal decorator, but when users run ``help()`` or other documentation tools on the returned wrapper function, they will see a function with the original function's name, signature, module name, etc. This function is similar in use to the ``@template_function`` decorator, but rather than generating the entire decorator function in one calling layer, it simply generates an extra layer for signature compatibility. NOTE: the function returned from ``rewrap()`` will have the same attribute ``__dict__`` as the original function, so if you need to set any function attributes you should do so on the function returned from ``rewrap()`` (or on the original function), and *not* on the wrapper you're passing in to ``rewrap()``. """ def rewrap(__original, __decorated): """return __decorated($args)""" return apply_template(rewrap, func, wrapper) if sys.version<"2.5": # We'll need this for monkeypatching linecache def checkcache(filename=None): """Discard cache entries that are out of date. (This is not checked upon each call!)""" if filename is None: filenames = linecache.cache.keys() else: if filename in linecache.cache: filenames = [filename] else: return for filename in filenames: size, mtime, lines, fullname = linecache.cache[filename] if mtime is None: continue # no-op for files loaded via a __loader__ try: stat = os.stat(fullname) except os.error: del linecache.cache[filename] continue if size != stat.st_size or mtime != stat.st_mtime: del linecache.cache[filename] def _cache_lines(filename, lines, owner=None): if owner is None: owner = filename else: from weakref import ref owner = ref(owner, lambda r: linecache and linecache.cache.__delitem__(filename)) global linecache; import linecache if sys.version<"2.5" and linecache.checkcache.__module__!=__name__: linecache.checkcache = checkcache linecache.cache[filename] = 0, None, lines, owner def cache_source(filename, source, owner=None): _cache_lines(filename, source.splitlines(True), owner) def template_function(wrapper=None): """Decorator that uses its wrapped function's docstring as a template Example:: def before_and_after(func): @template_function def wrap(__func, __message): ''' print "before", __message try: return __func($args) finally: print "after", __message ''' return wrap(func, "test") The above code will return individually-generated wrapper functions whose signature, defaults, ``__name__``, ``__module__``, and ``func_globals`` match those of the wrapped functions. You can use define any arguments you wish in the wrapping function, as long as the first argument is the function to be wrapped, and the arguments are named so as not to conflict with the arguments of the function being wrapped. (i.e., they should have relatively unique names.) Note that the function body will *not* have access to the globals of the calling module, as it is compiled with the globals of the *wrapped* function! Thus, any non-builtin values that you need in the wrapper should be passed in as arguments to the template function. """ if wrapper is None: return decorate_assignment(lambda f,k,v,o: template_function(v)) return apply_template.__get__(wrapper) def struct(*mixins, **kw): """Turn a function into a simple data structure class This decorator creates a tuple subclass with the same name and docstring as the decorated function. The class will have read-only properties with the same names as the function's arguments, and the ``repr()`` of its instances will look like a call to the original function. The function should return a tuple of values in the same order as its argument names, as it will be used by the class' constructor. The function can perform validation, add defaults, and/or do type conversions on the values. If the function takes a ``*``, argument, it should flatten this argument into the result tuple, e.g.:: @struct() def pair(first, *rest): return (first,) + rest The ``rest`` property of the resulting class will thus return a tuple for the ``*rest`` arguments, and the structure's ``repr()`` will reflect the way it was created. The ``struct()`` decorator takes optional mixin classes (as positional arguments), and dictionary entries (as keyword arguments). The mixin classes will be placed before ``tuple`` in the resulting class' bases, and the dictionary entries will be placed in the class' dictionary. These entries take precedence over any default entries (e.g. methods, properties, docstring, etc.) that are created by the ``struct()`` decorator. """ def callback(frame, name, func, old_locals): def __new__(cls, *args, **kw): result = func(*args, **kw) if type(result) is tuple: return tuple.__new__(cls, (cls,)+result) else: return result def __repr__(self): return name+tuple.__repr__(self[1:]) import inspect args, star, dstar, defaults = inspect.getargspec(func) d = dict( __new__ = __new__, __repr__ = __repr__, __doc__=func.__doc__, __module__ = func.__module__, __args__ = args, __star__ = star, __slots__ = [], ) for p,a in enumerate(args): if isinstance(a,str): d[a] = property(lambda self, p=p+1: self[p]) if star: d[star] = property(lambda self, p=len(args)+1: self[p:]) d.update(kw) return type(name, mixins+(tuple,), d) return decorate_assignment(callback) def frameinfo(frame): """Return (kind, module, locals, globals) tuple for a frame 'kind' is one of "exec", "module", "class", "function call", or "unknown". """ f_locals = frame.f_locals f_globals = frame.f_globals sameNamespace = f_locals is f_globals hasModule = '__module__' in f_locals hasName = '__name__' in f_globals sameName = hasModule and hasName sameName = sameName and f_globals['__name__']==f_locals['__module__'] module = hasName and sys.modules.get(f_globals['__name__']) or None namespaceIsModule = module and module.__dict__ is f_globals if not namespaceIsModule: # some kind of funky exec kind = "exec" if hasModule and not sameNamespace: kind="class" elif sameNamespace and not hasModule: kind = "module" elif sameName and not sameNamespace: kind = "class" elif not sameNamespace: kind = "function call" else: # How can you have f_locals is f_globals, and have '__module__' set? # This is probably module-level code, but with a '__module__' variable. kind = "unknown" return kind,module,f_locals,f_globals def decorate_class(decorator, depth=2, frame=None, allow_duplicates=False): """Set up `decorator` to be passed the containing class upon creation This function is designed to be called by a decorator factory function executed in a class suite. The factory function supplies a decorator that it wishes to have executed when the containing class is created. The decorator will be given one argument: the newly created containing class. The return value of the decorator will be used in place of the class, so the decorator should return the input class if it does not wish to replace it. The optional `depth` argument to this function determines the number of frames between this function and the targeted class suite. `depth` defaults to 2, since this skips the caller's frame. Thus, if you call this function from a function that is called directly in the class suite, the default will be correct, otherwise you will need to determine the correct depth value yourself. Alternately, you can pass in a `frame` argument to explicitly indicate what frame is doing the class definition. This function works by installing a special class factory function in place of the ``__metaclass__`` of the containing class. Therefore, only decorators *after* the last ``__metaclass__`` assignment in the containing class will be executed. Thus, any classes using class decorators should declare their ``__metaclass__`` (if any) *before* specifying any class decorators, to ensure that all class decorators will be applied.""" frame = enclosing_frame(frame, depth+1) kind, module, caller_locals, caller_globals = frameinfo(frame) if kind != "class": raise SyntaxError( "Class decorators may only be used inside a class statement" ) elif not allow_duplicates and has_class_decorator(decorator, None, frame): return previousMetaclass = caller_locals.get('__metaclass__') defaultMetaclass = caller_globals.get('__metaclass__', ClassType) def advise(name,bases,cdict): if '__metaclass__' in cdict: del cdict['__metaclass__'] if previousMetaclass is None: if bases: # find best metaclass or use global __metaclass__ if no bases meta = metaclass_for_bases(bases) else: meta = defaultMetaclass elif metaclass_is_decorator(previousMetaclass): # special case: we can't compute the "true" metaclass here, # so we need to invoke the previous metaclass and let it # figure it out for us (and apply its own advice in the process) meta = previousMetaclass else: meta = metaclass_for_bases(bases, previousMetaclass) newClass = meta(name,bases,cdict) # this lets the decorator replace the class completely, if it wants to return decorator(newClass) # introspection data only, not used by inner function # Note: these attributes cannot be renamed or it will break compatibility # with zope.interface and any other code that uses this decoration protocol advise.previousMetaclass = previousMetaclass advise.callback = decorator # install the advisor caller_locals['__metaclass__'] = advise def metaclass_is_decorator(ob): """True if 'ob' is a class advisor function""" return isinstance(ob,FunctionType) and hasattr(ob,'previousMetaclass') def iter_class_decorators(depth=2, frame=None): frame = enclosing_frame(frame, depth+1) m = frame.f_locals.get('__metaclass__') while metaclass_is_decorator(m): yield getattr(m, 'callback', None) m = m.previousMetaclass def has_class_decorator(decorator, depth=2, frame=None): return decorator in iter_class_decorators(0, frame or sys._getframe(depth)) def metaclass_for_bases(bases, explicit_mc=None): """Determine metaclass from 1+ bases and optional explicit __metaclass__""" meta = [getattr(b,'__class__',type(b)) for b in bases] if explicit_mc is not None: # The explicit metaclass needs to be verified for compatibility # as well, and allowed to resolve the incompatible bases, if any meta.append(explicit_mc) if len(meta)==1: # easy case return meta[0] classes = [c for c in meta if c is not ClassType] candidates = [] for m in classes: for n in classes: if issubclass(n,m) and m is not n: break else: # m has no subclasses in 'classes' if m in candidates: candidates.remove(m) # ensure that we're later in the list candidates.append(m) if not candidates: # they're all "classic" classes return ClassType elif len(candidates)>1: # We could auto-combine, but for now we won't... raise TypeError("Incompatible metatypes",bases) # Just one, return it return candidates[0] def decorate_assignment(callback, depth=2, frame=None): """Invoke 'callback(frame,name,value,old_locals)' on next assign in 'frame' The frame monitored is determined by the 'depth' argument, which gets passed to 'sys._getframe()'. When 'callback' is invoked, 'old_locals' contains a copy of the frame's local variables as they were before the assignment took place, allowing the callback to access the previous value of the assigned variable, if any. The callback's return value will become the new value of the variable. 'name' is the name of the variable being created or modified, and 'value' is its value (the same as 'frame.f_locals[name]'). This function also returns a decorator function for forward-compatibility with Python 2.4 '@' syntax. Note, however, that if the returned decorator is used with Python 2.4 '@' syntax, the callback 'name' argument may be 'None' or incorrect, if the 'value' is not the original function (e.g. when multiple decorators are used). """ frame = enclosing_frame(frame, depth+1) oldtrace = [frame.f_trace] old_locals = frame.f_locals.copy() def tracer(frm,event,arg): if event=='call': # We don't want to trace into any calls if oldtrace[0]: # ...but give the previous tracer a chance to, if it wants return oldtrace[0](frm,event,arg) else: return None try: if frm is frame and event !='exception': # Aha, time to check for an assignment... for k,v in frm.f_locals.items(): if k not in old_locals or old_locals[k] is not v: break else: # No luck, keep tracing return tracer # Got it, fire the callback, then get the heck outta here... frm.f_locals[k] = callback(frm,k,v,old_locals) finally: # Give the previous tracer a chance to run before we return if oldtrace[0]: # And allow it to replace our idea of the "previous" tracer oldtrace[0] = oldtrace[0](frm,event,arg) uninstall() return oldtrace[0] def uninstall(): # Unlink ourselves from the trace chain. frame.f_trace = oldtrace[0] sys.settrace(oldtrace[0]) # Install the trace function frame.f_trace = tracer sys.settrace(tracer) def do_decorate(f): # Python 2.4 '@' compatibility; call the callback uninstall() frame = sys._getframe(1) return callback( frame, getattr(f,'__name__',None), f, frame.f_locals ) return do_decorate PK•Tî6è ånVnVpeak/util/decorators.pyc;ò zÞ˜Fc @s6dklZlZdkZdkZdddddddd d d d g Zd „Zedd„Zd„Z d„Z d„Z d„Z ei djoed„Zned„Zed„Zed„Zd„Zd„Zdeed„Zd„Zded„Zded„Zed „Zded!„ZdS("(s ClassTypes FunctionTypeNsdecorate_classsmetaclass_is_decoratorsmetaclass_for_basess frameinfosdecorate_assignmentsdecoratesstructstemplate_functionsrewraps cache_sourcesenclosing_framecsGtˆƒdjotˆƒ‰ˆiƒn‡d†}t|ƒSdS(sÐUse Python 2.4 decorators w/Python 2.3+ Example:: class Foo(object): decorate(classmethod) def something(cls,etc): """This is a classmethod""" You can pass in more than one decorator, and they are applied in the same order that would be used for ``@`` decorators in Python 2.4. This function can be used to write decorator-using code that will work with both Python 2.3 and 2.4 (and up). ics%xˆD]}||ƒ}qW|SdS(N(s decoratorssdsv(sframesksvs old_localssd(s decorators(s-build\bdist.win32\egg\peak\util\decorators.pyscallbacksN(slens decoratorsslistsreversescallbacksdecorate_assignment(s decoratorsscallback((s decoratorss-build\bdist.win32\egg\peak\util\decorators.pysdecorate s   icCsH|p ti|ƒ}x'|iidƒtjo |i}qW|SdS(s>Get an enclosing frame that skips DecoratorTools callback codes__name__N(sframessyss _getframeslevels f_globalssgets__name__sf_back(sframeslevel((s-build\bdist.win32\egg\peak\util\decorators.pysenclosing_frame$s cCsldkl}l}|i}|djo d}n||ƒ\}}}}|||||ƒdd!fSdS(N(s formatargspecs getargspecss anonymousiiÿÿÿÿ( sinspects formatargspecs getargspecsfuncs__name__sfuncnamesargssvarargsskwargssdefaults(sfuncs formatargspecsdefaultsskwargssargssfuncnamesvarargss getargspec((s-build\bdist.win32\egg\peak\util\decorators.pys name_and_spec*s    cCs-|i}|o|d|ip|iSdS(Ns.(sfuncs __module__sms__name__(sfuncsm((s-build\bdist.win32\egg\peak\util\decorators.pysqname3s c Nsöe|ƒ\}} e|ƒ\}} |iiddƒiddƒ}h}d|d}|e ƒ;}de |ƒe |ƒe |ƒf} e|| dƒ|i|U|||||Ž}e| ||ƒ|i|_|i|_|i|_|SdS( Ns%s%%s$argss %(argspec)ssA def %(wrapname)s(%(wrapspec)s): def %(funcname)s(%(argspec)s): s return %(funcname)s s<%s wrapping %s at 0x%08X>sexec(s name_and_specsfuncsfuncnamesargspecswrapperswrapnameswrapspecs__doc__sreplacesbodysdslocalssqnamesidsfilenamescompiles func_globalssargsskwsfs cache_sources func_defaultss__dict__( swrappersfuncsargsskwsbodysdsfswrapnamesfuncnamesargspecswrapspecsfilename((s-build\bdist.win32\egg\peak\util\decorators.pysapply_template8s! %   cCsd„}t|||ƒSdS(sCreate a wrapper with the signature of `func` and a body of `wrapper` Example:: def before_and_after(func): def decorated(*args, **kw): print "before" try: return func(*args, **kw) finally: print "after" return rewrap(func, decorated) The above function is a normal decorator, but when users run ``help()`` or other documentation tools on the returned wrapper function, they will see a function with the original function's name, signature, module name, etc. This function is similar in use to the ``@template_function`` decorator, but rather than generating the entire decorator function in one calling layer, it simply generates an extra layer for signature compatibility. NOTE: the function returned from ``rewrap()`` will have the same attribute ``__dict__`` as the original function, so if you need to set any function attributes you should do so on the function returned from ``rewrap()`` (or on the original function), and *not* on the wrapper you're passing in to ``rewrap()``. cCsdS(sreturn __decorated($args)N((s __originals __decorated((s-build\bdist.win32\egg\peak\util\decorators.pysrewrappsN(srewrapsapply_templatesfuncswrapper(sfuncswrappersrewrap((s-build\bdist.win32\egg\peak\util\decorators.pysrewrapSs s2.5cCsê|tjotiiƒ}n"|tijo |g}ndSx¢|D]š}ti|\}}}}|tjoqHnyt i |ƒ}Wn#t i j oti|=qHnX||i jp ||ijoti|=qHqHWdS(sYDiscard cache entries that are out of date. (This is not checked upon each call!)N(sfilenamesNones linecachescacheskeyss filenamesssizesmtimeslinessfullnamesossstatserrorsst_sizesst_mtime(sfilenameslinessstats filenamessmtimesfullnamessize((s-build\bdist.win32\egg\peak\util\decorators.pys checkcache~s$     cs|tjo ˆ}n#dkl}||‡d†ƒ}dkatidjotii t jo tt_ndt||fti ˆšss2.5i( sownersNonesfilenamesweakrefsrefs linecachessyssversions checkcaches __module__s__name__slinesscache(sfilenameslinessownersref((sfilenames-build\bdist.win32\egg\peak\util\decorators.pys _cache_lines•s    # cCst||itƒ|ƒdS(N(s _cache_linessfilenamessources splitlinessTruesowner(sfilenamessourcesowner((s-build\bdist.win32\egg\peak\util\decorators.pys cache_source scCs/|tjotd„ƒSnti|ƒSdS(sËDecorator that uses its wrapped function's docstring as a template Example:: def before_and_after(func): @template_function def wrap(__func, __message): ''' print "before", __message try: return __func($args) finally: print "after", __message ''' return wrap(func, "test") The above code will return individually-generated wrapper functions whose signature, defaults, ``__name__``, ``__module__``, and ``func_globals`` match those of the wrapped functions. You can use define any arguments you wish in the wrapping function, as long as the first argument is the function to be wrapped, and the arguments are named so as not to conflict with the arguments of the function being wrapped. (i.e., they should have relatively unique names.) Note that the function body will *not* have access to the globals of the calling module, as it is compiled with the globals of the *wrapped* function! Thus, any non-builtin values that you need in the wrapper should be passed in as arguments to the template function. cCs t|ƒS(N(stemplate_functionsv(sfsksvso((s-build\bdist.win32\egg\peak\util\decorators.pysÅsN(swrappersNonesdecorate_assignmentsapply_templates__get__(swrapper((s-build\bdist.win32\egg\peak\util\decorators.pystemplate_function¥s cs‡‡d†}t|ƒSdS(s‰Turn a function into a simple data structure class This decorator creates a tuple subclass with the same name and docstring as the decorated function. The class will have read-only properties with the same names as the function's arguments, and the ``repr()`` of its instances will look like a call to the original function. The function should return a tuple of values in the same order as its argument names, as it will be used by the class' constructor. The function can perform validation, add defaults, and/or do type conversions on the values. If the function takes a ``*``, argument, it should flatten this argument into the result tuple, e.g.:: @struct() def pair(first, *rest): return (first,) + rest The ``rest`` property of the resulting class will thus return a tuple for the ``*rest`` arguments, and the structure's ``repr()`` will reflect the way it was created. The ``struct()`` decorator takes optional mixin classes (as positional arguments), and dictionary entries (as keyword arguments). The mixin classes will be placed before ``tuple`` in the resulting class' bases, and the dictionary entries will be placed in the class' dictionary. These entries take precedence over any default entries (e.g. methods, properties, docstring, etc.) that are created by the ``struct()`` decorator. cs‡d†}‡d†} dk}|iˆƒ\}}} }t d|d| dˆi dˆi d|d|d gƒ} xHt |ƒD]:\} } t| tƒot| d d „ƒ| | scCs||S(N(sselfsp(sselfsp((s-build\bdist.win32\egg\peak\util\decorators.pyss(s__new__s__repr__sinspects getargspecsfuncsargssstarsdstarsdefaultssdicts__doc__s __module__sds enumeratespsas isinstancesstrspropertyslensupdateskwstypesnamesmixinsstuple(sframesnamesfuncs old_localss__new__sinspectsstarsdefaultssargssdsasps__repr__sdstar(smixinsskw(snamesfuncs-build\bdist.win32\egg\peak\util\decorators.pyscallbackës     "$ N(scallbacksdecorate_assignment(smixinsskwscallback((smixinsskws-build\bdist.win32\egg\peak\util\decorators.pysstructÎsc Cs!|i}|i}||j}d|j}d|j}|o|}|o|d|dj}|otii |dƒpt }|o |i |j}| o#d} |o| o d} q nK|o| o d} n2|o| o d} n| o d} nd} | |||fSdS( sReturn (kind, module, locals, globals) tuple for a frame 'kind' is one of "exec", "module", "class", "function call", or "unknown". s __module__s__name__sexecsclasssmodules function callsunknownN(sframesf_localss f_globalss sameNamespaces hasModuleshasNamessameNamessyssmodulessgetsNonesmodules__dict__snamespaceIsModuleskind( sframes sameNamespacesnamespaceIsModules f_globalssmodulessameNames hasModulesf_localsshasNameskind((s-build\bdist.win32\egg\peak\util\decorators.pys frameinfo s,      $   ic s¾t||dƒ}t|ƒ\}}}}|djotdƒ‚n$| ot ˆt |ƒodSn|i dƒ‰|i dtƒ‰‡‡‡d†} ˆ| _ˆ| _| |dGet an enclosing frame that skips DecoratorTools callback codes__name__N(sframessyss _getframeslevels f_globalssgets__name__sf_back(sframeslevel((s-build\bdist.win32\egg\peak\util\decorators.pysenclosing_frame$s cCsldkl}l}|i}|djo d}n||ƒ\}}}}|||||ƒdd!fSdS(N(s formatargspecs getargspecss anonymousiiÿÿÿÿ( sinspects formatargspecs getargspecsfuncs__name__sfuncnamesargssvarargsskwargssdefaults(sfuncs formatargspecsdefaultsskwargssargssfuncnamesvarargss getargspec((s-build\bdist.win32\egg\peak\util\decorators.pys name_and_spec*s    cCs-|i}|o|d|ip|iSdS(Ns.(sfuncs __module__sms__name__(sfuncsm((s-build\bdist.win32\egg\peak\util\decorators.pysqname3s c Nsöe|ƒ\}} e|ƒ\}} |iiddƒiddƒ}h}d|d}|e ƒ;}de |ƒe |ƒe |ƒf} e|| dƒ|i|U|||||Ž}e| ||ƒ|i|_|i|_|i|_|SdS( Ns%s%%s$argss %(argspec)ssA def %(wrapname)s(%(wrapspec)s): def %(funcname)s(%(argspec)s): s return %(funcname)s s<%s wrapping %s at 0x%08X>sexec(s name_and_specsfuncsfuncnamesargspecswrapperswrapnameswrapspecs__doc__sreplacesbodysdslocalssqnamesidsfilenamescompiles func_globalssargsskwsfs cache_sources func_defaultss__dict__( swrappersfuncsargsskwsbodysdsfswrapnamesfuncnamesargspecswrapspecsfilename((s-build\bdist.win32\egg\peak\util\decorators.pysapply_template8s! %   cCsd„}t|||ƒSdS(sCreate a wrapper with the signature of `func` and a body of `wrapper` Example:: def before_and_after(func): def decorated(*args, **kw): print "before" try: return func(*args, **kw) finally: print "after" return rewrap(func, decorated) The above function is a normal decorator, but when users run ``help()`` or other documentation tools on the returned wrapper function, they will see a function with the original function's name, signature, module name, etc. This function is similar in use to the ``@template_function`` decorator, but rather than generating the entire decorator function in one calling layer, it simply generates an extra layer for signature compatibility. NOTE: the function returned from ``rewrap()`` will have the same attribute ``__dict__`` as the original function, so if you need to set any function attributes you should do so on the function returned from ``rewrap()`` (or on the original function), and *not* on the wrapper you're passing in to ``rewrap()``. cCsdS(sreturn __decorated($args)N((s __originals __decorated((s-build\bdist.win32\egg\peak\util\decorators.pysrewrappsN(srewrapsapply_templatesfuncswrapper(sfuncswrappersrewrap((s-build\bdist.win32\egg\peak\util\decorators.pysrewrapSs s2.5cCsê|tjotiiƒ}n"|tijo |g}ndSx¢|D]š}ti|\}}}}|tjoqHnyt i |ƒ}Wn#t i j oti|=qHnX||i jp ||ijoti|=qHqHWdS(sYDiscard cache entries that are out of date. (This is not checked upon each call!)N(sfilenamesNones linecachescacheskeyss filenamesssizesmtimeslinessfullnamesossstatserrorsst_sizesst_mtime(sfilenameslinessstats filenamessmtimesfullnamessize((s-build\bdist.win32\egg\peak\util\decorators.pys checkcache~s$     cs|tjo ˆ}n#dkl}||‡d†ƒ}dkatidjotii t jo tt_ndt||fti ˆšss2.5i( sownersNonesfilenamesweakrefsrefs linecachessyssversions checkcaches __module__s__name__slinesscache(sfilenameslinessownersref((sfilenames-build\bdist.win32\egg\peak\util\decorators.pys _cache_lines•s    # cCst||itƒ|ƒdS(N(s _cache_linessfilenamessources splitlinessTruesowner(sfilenamessourcesowner((s-build\bdist.win32\egg\peak\util\decorators.pys cache_source scCs/|tjotd„ƒSnti|ƒSdS(sËDecorator that uses its wrapped function's docstring as a template Example:: def before_and_after(func): @template_function def wrap(__func, __message): ''' print "before", __message try: return __func($args) finally: print "after", __message ''' return wrap(func, "test") The above code will return individually-generated wrapper functions whose signature, defaults, ``__name__``, ``__module__``, and ``func_globals`` match those of the wrapped functions. You can use define any arguments you wish in the wrapping function, as long as the first argument is the function to be wrapped, and the arguments are named so as not to conflict with the arguments of the function being wrapped. (i.e., they should have relatively unique names.) Note that the function body will *not* have access to the globals of the calling module, as it is compiled with the globals of the *wrapped* function! Thus, any non-builtin values that you need in the wrapper should be passed in as arguments to the template function. cCs t|ƒS(N(stemplate_functionsv(sfsksvso((s-build\bdist.win32\egg\peak\util\decorators.pysÅsN(swrappersNonesdecorate_assignmentsapply_templates__get__(swrapper((s-build\bdist.win32\egg\peak\util\decorators.pystemplate_function¥s cs‡‡d†}t|ƒSdS(s‰Turn a function into a simple data structure class This decorator creates a tuple subclass with the same name and docstring as the decorated function. The class will have read-only properties with the same names as the function's arguments, and the ``repr()`` of its instances will look like a call to the original function. The function should return a tuple of values in the same order as its argument names, as it will be used by the class' constructor. The function can perform validation, add defaults, and/or do type conversions on the values. If the function takes a ``*``, argument, it should flatten this argument into the result tuple, e.g.:: @struct() def pair(first, *rest): return (first,) + rest The ``rest`` property of the resulting class will thus return a tuple for the ``*rest`` arguments, and the structure's ``repr()`` will reflect the way it was created. The ``struct()`` decorator takes optional mixin classes (as positional arguments), and dictionary entries (as keyword arguments). The mixin classes will be placed before ``tuple`` in the resulting class' bases, and the dictionary entries will be placed in the class' dictionary. These entries take precedence over any default entries (e.g. methods, properties, docstring, etc.) that are created by the ``struct()`` decorator. cs‡d†}‡d†} dk}|iˆƒ\}}} }t d|d| dˆi dˆi d|d|d gƒ} xHt |ƒD]:\} } t| tƒot| d d „ƒ| | scCs||S(N(sselfsp(sselfsp((s-build\bdist.win32\egg\peak\util\decorators.pyss(s__new__s__repr__sinspects getargspecsfuncsargssstarsdstarsdefaultssdicts__doc__s __module__sds enumeratespsas isinstancesstrspropertyslensupdateskwstypesnamesmixinsstuple(sframesnamesfuncs old_localss__new__sinspectsstarsdefaultssargssdsasps__repr__sdstar(smixinsskw(snamesfuncs-build\bdist.win32\egg\peak\util\decorators.pyscallbackës     "$ N(scallbacksdecorate_assignment(smixinsskwscallback((smixinsskws-build\bdist.win32\egg\peak\util\decorators.pysstructÎsc Cs!|i}|i}||j}d|j}d|j}|o|}|o|d|dj}|otii |dƒpt }|o |i |j}| o#d} |o| o d} q nK|o| o d} n2|o| o d} n| o d} nd} | |||fSdS( sReturn (kind, module, locals, globals) tuple for a frame 'kind' is one of "exec", "module", "class", "function call", or "unknown". s __module__s__name__sexecsclasssmodules function callsunknownN(sframesf_localss f_globalss sameNamespaces hasModuleshasNamessameNamessyssmodulessgetsNonesmodules__dict__snamespaceIsModuleskind( sframes sameNamespacesnamespaceIsModules f_globalssmodulessameNames hasModulesf_localsshasNameskind((s-build\bdist.win32\egg\peak\util\decorators.pys frameinfo s,      $   ic s¾t||dƒ}t|ƒ\}}}}|djotdƒ‚n$| ot ˆt |ƒodSn|i dƒ‰|i dtƒ‰‡‡‡d†} ˆ| _ˆ| _| |d