def decorator(fn):
def wrapper(*args, **kwargs):
print 'With sour cream and chives!',
return fn(*args, **kwargs)
return wrapper
class Potato(object):
def __call__(self):
print 'Potato @ {} called'.format(id(self))
spud = Potato()
fancy_spud = decorator(Potato())
With this code we have two instances of callable class, one is decorated and one is plain:
>>> spud()
Potato @ 140408136280592 called
>>> fancy_spud()
With sour cream and chives! Potato @ 140408134310864 called
I wonder if it is somehow supported to use the @decorator
syntax on a callable for just one instance - as opposed to decorating the class / method, which would apply to every instance. According to this popular answer, the @syntax is just sugar for:
function = decorator(function)
But is it an over-simplification? With all my half-baked attempts it seems only to work when the syntax occurs before def
, class
, whitespace or @another_decorator
.
@decorator
baked = Potato()
That's a SyntaxError
.
baked = Potato()
@decorator
baked
Also SyntaxError
.
@decorator
def baked(_spud=Potato()):
return _spud()
Works, but is ugly and kinda cheating.