Given a function foo
:
def foo(x):
pass
Printing its representation by invoking str
or repr
gives you something boring like this:
str(foo)
'<function foo at 0x119e0c8c8>'
I'd like to know if it is possible to override a function's __str__
method to print something else. Essentially, I'd like to do:
str(foo)
"I'm foo!'
Now, I understand that the description of a function should come from __doc__
which is the function's docstring. However, this is merely an experiment.
In attempting to figure out a solution to this problem, I came across implementing __str__
for classes
: How to define a __str__ method for a class?
This approach involved defining a metaclass with an __str__
method, and then attempting to assign the __metaclass__
hook in the actual class.
I wondered whether the same could be done to the class function
, so here's what I tried -
In [355]: foo.__class__
Out[355]: function
In [356]: class fancyfunction(type):
...: def __str__(self):
...: return self.__name__
...:
In [357]: foo.__class__.__metaclass__ = fancyfunction
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
I figured it wouldn't work, but it was worth a shot!
So, what's the best way to implement __str__
for a function?