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

Timo Schmiade the_isz at gmx.de
Tue Apr 19 09:12:13 CEST 2011


Hey Wayne,

On Mon, Apr 18, 2011 at 04:04:15PM -0700, Wayne Witzel III wrote:
> 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

Brilliant! I didn't realize you could use member functions as
decorators, too! That way, you can easily create closures to self,
solving all the problems I was seeing.

Just one question remains now: What is a "Borg" in this context?

Thank you.

Timo



More information about the Python-list mailing list