I've only seen examples for setting the __repr__
method in class definitions. Is it possible to change the __repr__
for functions either in their definitions or after defining them?
I've attempted without success...
>>> def f(): pass >>> f <function f at 0x1026730c8> >>> f.__repr__ = lambda: '<New repr>' >>> f <function __main__.f>
Python __repr__() function returns the object representation in string format. This method is called when repr() function is invoked on the object. If possible, the string returned should be a valid Python expression that can be used to reconstruct the object again.
Python repr() Function returns a printable representation of an object in Python.
In general, methods in Python either mutate the object or return a value.
__repr__ (self) Returns a string as a representation of the object. Ideally, the representation should be information-rich and could be used to recreate an object with the same value.
Yes, if you're willing to forgo the function actually being a function.
First, define a class for our new type:
import functools class reprwrapper(object): def __init__(self, repr, func): self._repr = repr self._func = func functools.update_wrapper(self, func) def __call__(self, *args, **kw): return self._func(*args, **kw) def __repr__(self): return self._repr(self._func)
Add in a decorator function:
def withrepr(reprfun): def _wrap(func): return reprwrapper(reprfun, func) return _wrap
And now we can define the repr along with the function:
@withrepr(lambda x: "<Func: %s>" % x.__name__) def mul42(y): return y*42
Now repr(mul42)
produces '<Func: mul42>'
No, because repr(f)
is done as type(f).__repr__(f)
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With