vajrasky vajrasky - 10 months ago 46
Python Question

How do I change the representation of a Python function?

>>> def hehe():
... return "spam"
>>> repr(hehe)
'<function hehe at 0x7fe5624e29b0>'

I want to have:

>>> repr(hehe)
'hehe function created by awesome programmer'

How do I do that? Putting
function does not work.


In case you guys are wondering why I want to do this:

>>> defaultdict(hehe)
defaultdict(<function hehe at 0x7f0e0e252280>, {})

I just don't like the way it shows here.


Usually, when you want to change something about the function, say function signature, function behavior or function attributes, you should consider using a decorator. So here is how you might implement what you want:

class change_repr(object):
    def __init__(self, functor):
        self.functor = functor

        #  lets copy some key attributes from the original function
        self.__name__ = functor.__name__
        self.__doc__ = functor.__doc__

    def __call__(self, *args, **kwargs):
        return self.functor(*args, **kwargs)

    def __repr__(self):
        return '<function %s created by ...>' % self.functor.__name__

def f():
    return 'spam'

print f()  # spam
print repr(f)  # <function hehe created by ...>

Note, that you can only use class based decorator, since you need to override __repr__ method, which you can't do with a function object.