I tried to ensure that my class-based decorator supported the behavior of the repr()original wrapped function (according to how the decorator functools.wrapsworks on functions). I am using python 3.3.
First I tried functools:
import functools
class ClassBasedDecorator():
def __init__(self, fn):
self.fn = fn
functools.update_wrapper(self, fn)
def __call__(self, *args, **kwargs):
self.fn(*args, **kwargs)
@ClassBasedDecorator
def wrapped(text):
pass
But when I call repr()on the decorated function, I get:
>>> repr(wrapped)
'<__main__.ClassBasedDecorator object at 0x2d8860b6850>'
Ok, so I tried setting up __repr__my decorator method , which should be called repr().
Use functools again:
class ClassBasedDecorator():
def __init__(self, fn):
self.fn = fn
functools.update_wrapper(
self, fn,
assigned=functools.WRAPPER_ASSIGNMENTS + ('__repr__',)
)
def __call__(self, *args, **kwargs):
self.fn(*args, **kwargs)
It does not change the output, but something interesting happens:
>>> repr(wrapped)
'<__main__.ClassBasedDecorator object at 0x2d8860b69d0>'
>>> wrapped.__repr__()
'<function wrapped at 0x2d8860a9710>'
Explicitly setting the __repr__decorator instance method has the same effect.
repr(instance) instance.__class__.__repr__(instance). , overriden __repr__ .
, :
repr(instance) instance.__class__.__repr__(instance) instance.__repr__()? - ?- ,
functools.wraps , ( repr() )?