One use case that I can think of is if you want to wrap all class methods with a single function decorator. Let's say you have the following decorator:
def logit(f): def res(*args, **kwargs): print "Calling %s" % f.__name__ return f(*args, **kwargs) return res
And the following class:
>>> class Pointless: def foo(self): print 'foo' def bar(self): print 'bar' def baz(self): print 'baz' >>> p = Pointless() >>> p.foo(); p.bar(); p.baz() foo bar baz
You can decorate all methods:
>>> class Pointless: @logit def foo(self): print 'foo' @logit def bar(self): print 'bar' @logit def baz(self): print 'baz' >>> p = Pointless() >>> p.foo(); p.bar(); p.baz() Calling foo foo Calling bar bar Calling baz baz
But this is LAME! Instead, you can do this:
>>> def logall(cls): for a in dir(cls): if callable(getattr(cls, a)): setattr(cls, a, logit(getattr(cls, a))) return cls >>> @logall class Pointless: def foo(self): print 'foo' def bar(self): print 'bar' def baz(self): print 'baz' >>> p = Pointless() >>> p.foo(); p.bar(); p.baz() Calling foo foo Calling bar bar Calling baz baz
UPDATE: a more general version of logall :
>>> def wrapall(method): def dec(cls): for a in dir(cls): if callable(getattr(cls, a)): setattr(cls, a, method(getattr(cls, a))) return cls return dec >>> @wrapall(logit) class Pointless: def foo(self): print 'foo' def bar(self): print 'bar' def baz(self): print 'baz' >>> p = Pointless() >>> p.foo(); p.bar(); p.baz() Calling foo foo Calling bar bar Calling baz baz >>>
Full disclosure: I never had to do this, and I just made this example.
Claudiu
source share