I want to create a decorator (with tag) that performs pre / post processing of the function as shown below and reuse it.
>>> @MyDecorator('any-tag')
... def foo():
... print u'foo'
...
>>> foo():
pre-action. tag=any-tag.
foo
post-action. tag=any-tag.
Make it like this.
class MyDecorator(object):
def __init__(self, tag):
self._tag = tag
def __call__(self, f0):
def decorated(*args, **kwargs):
print u'pre-action. tag=' + self._tag
ret = f0(*args, **kwargs)
print u'post-action. tag=' + self._tag
return ret
return decorated
Version using functools.wraps.
Thank you @termoshtt (^ ◇ ^)
from functools import wraps
def MyDecorator(tag):
def dec(f0):
@wraps(f0)
def decorated(*args, **kwargs):
print u'pre-action. tag=' + tag
ret = f0(*args, **kwargs)
print u'post-action. tag=' + tag
return ret
return decorated
return dec
Recommended Posts