Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to change a function's repr in python?

Tags:

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> 
like image 339
beardc Avatar asked Jun 04 '12 01:06

beardc


People also ask

What does __ repr __ mean in Python?

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.

What does repr () do in Python?

Python repr() Function returns a printable representation of an object in Python.

Can methods modify object Python?

In general, methods in Python either mutate the object or return a value.

What is def __ repr __( self?

__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.


2 Answers

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>'

like image 78
kwatford Avatar answered Sep 22 '22 14:09

kwatford


No, because repr(f) is done as type(f).__repr__(f) instead.

like image 29
JBernardo Avatar answered Sep 19 '22 14:09

JBernardo