Decorator Maker is working. What do you think?

Ron_Adam radam2 at tampabay.rr.com
Tue Apr 5 01:38:30 EDT 2005



Hi again,  If anyone is reading this.

Fixed the endless loop when stacking the same decorator instance.  You
can now reuse the same exact decorator object either in stacks or on
different functions with different arguments.

The only quirk left is if you stack the same decorator object, and
have arguments on some, but not others.  The arguments get processed
first while preprocessing, and last when postprocessing.  That
shouldn't be a problem though and is easy to avoid by using an empty
argument lists where they are needed.

Let me know if there are still any problems with it.  I know someone
will find this useful.

Cheers,
Ron


(I left off the tests as they were getting to be quite long.)

#---start---

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

    self.function - the function decorated.
    self.arg - argument list passed by decorator
    self.preprocess - over ride to preprocess function arguments
    self.postprocess - over ride to postprocess function results
    """
    def __init__(self):
        self.function = None
        self.arglist = []
        self.arg = None
        self._number = 0
               
    def __call__(self, *arg):        
        if '<function ' in str(arg):
            def _wrapper(*args):
                try:
                    self.arg = self.arglist[self._number]
                    self._number += 1
                except IndexError:
                    self.arg = None
                pre_args = self.preprocess(*args)
                if type(pre_args) is not tuple:
                    pre_args = (pre_args,)
                result = _wrapper.function(*pre_args)
                result =  self.postprocess(result)
                try:
                    self._number -= 1
                    self.arg = self.arglist[self._number-1]
                    if self._number == 0:
                        self.arglist = []
                        self.function = None
                        self.arg = None
                except IndexError:
                    self.arg = None
                return result
            _wrapper.function = arg[0]
            return _wrapper
        self.arglist.append(arg)
        return self
    
    def preprocess(self, *args):
        #
        #   Over ride this method.
        #
        return args
    
    def postprocess(self, result):
        #
        #   Over ride this method.
        #
        return result

#---end---



More information about the Python-list mailing list