Decorator Base Class: Needs improvement.

Ron_Adam radam2 at tampabay.rr.com
Mon Apr 4 16:02:51 EDT 2005


Hi, Thanks again for all the helping me understand the details of
decorators. 

I put together a class to create decorators that could make them a lot
easier to use.  

It still has a few glitches in it that needs to be addressed.  

(1) The test for the 'function' object needs to not test for a string
but an object type instead.  

(2) If the same decorator instance is stacked, it will get locked in a
loop.  But stacking different instances created from the same
decorator object works fine. 

(3) It has trouble if a decorator has more than one argument.
  

But I think all of these things can be fixed.  Would this be something
that could go in the builtins library? (After any issues are fixed
first of course.)

When these are stacked, they process all the prepossess's first, call
the decorator, then process all the postprocess's. It just worked out
that way, which was a nice surprise and makes this work a bit
different than the standard decorators.

Cheers,
Ron

#---start---

class Decorator(object):
    """
    Decorator - A class to make decorators with.

    self.function - name of function decorated.
    self.arglist - arguments of decorator
    self.preprocess - over ride to preprocess function arguments.
    self.postprocess - over ride to postprocess function 
						return value.
    
    Example use:
        class mydecorator(Decorate):
        def self.preprocess(self, args):
            # process args
            return args
        def self.postprocess(self, results):
            # process results
            return results

        deco = mydecorator()

        @deco
        def function(args):
            # function body
            return args
    """
    function = None
    arglist = []
    def __call__(self, arg):
        self.arglist.append(arg)        
        def _wrapper( args):
            pre_args = self.preprocess(args)
            result = self.function(pre_args)
            return self.postprocess(result)
        if 'function' in str(arg):
            self.arglist = self.arglist[:-1]
            self.function = arg
            return _wrapper
        return self            
    def preprocess(self, args):
        return args
    def postprocess(self, result):
        return result

class mydecorator(Decorater):
    def preprocess(self, args):
        args = 2*args
        return args
    def postprocess(self, args):
        args = args.upper()
        args = args + str(self.arglist[0])
        return args
deco = mydecorator()

@deco('xyz')
def foo(text):        
    return text
  
print foo('abc')


#---end---





More information about the Python-list mailing list