How to create a (transparent) decorator with status information?

Wayne Witzel III wwitzel3 at gmail.com
Tue Apr 19 01:04:15 CEST 2011


> 
> Thinking object-orientedly, my first idea was to use an object as a
> decorator:
> 
> class CallCounter:
>   def __init__(self, decorated):
>     self.__function = decorated
>     self.__numCalls = 0
> 
>   def __call__(self, *args, **kwargs):
>     self.__numCalls += 1
>     return self.__function(*args, **kwargs)
> 
>   # To support decorating member functions
>   def __get__(self, obj, objType):
>     return functools.partial(self.__call__, obj)
> 
> This approach however has three problems (let "decorated" be a function
> decorated by either call_counts or CallCounter):
> 
> * The object is not transparent to the user like call_counts is. E.g.
>   help(decorated) will return CallCounter's help and decorated.func_name
>   will result in an error although decorated is a function.
> * The maintained status is not shared among multiple instances of the
>   decorator. This is unproblematic in this case, but might be a problem
>   in others (e.g. logging to a file).
> * I can't get the information from the decorator, so unless CallCounter
>   emits the information on its own somehow (e.g. by using print), the
>   decorator is completely pointless.
> 

Going with the object approach, you could use Borg to give yourself the state between instances you mentioned. And since you are using an object, you'll have access to the data without needing to return it from the decorator.

class StatefulDecorators(object):
    _state = {}
    def __new__(cls, *p, **k):
        self = object.__new__(cls, *p, **k)
        self.__dict__ = cls._state
        return self
            
    def count_calls(self, function):
        @functools.wraps(function)
        def wrapper(*args, **kwargs):
            try:
                self.calls += 1
            except AttributeError:
                self.calls = 1
            return function(*args, **kwargs)
        return wrapper

>>> sd = StatefulDecorators()
>>> @sd.count_calls
... def test():
...     pass
>>> test()
>>> sd.calls
1
>>> sd1 = StatefulDecorators()
>>> @sd1.count_calls
... def test2():
...     pass
>>> test2()
>>> sd1.calls
2
>>> sd.calls
2




More information about the Python-list mailing list