custom print statement for python function objects
functional-programming, python
Solution
Few errors:
>>> def f():
... pass
...
>>> g = f() <---- g is the return value of running f
>>> print g
None
in the first case, when you call print, you are calling a string representation of f
>>> f = F()
>>> print f <----- f is an instance of class F and
<----- print f tries to provide a suitable string representation
<----- by calling f.__str__
You should use doc strings for your motives
>>> def f():
... " some doc"
... pass
...
>>>
>>> f.__doc__
' some doc'
>>>
What you are trying to do is override the method wrapper `__str__`.
>>> def f():
... "some documentation .."
... pass
...
>>>
>>> f.__str__
<method-wrapper '__str__' of function object at 0x100430140>
>>>
Problem
I know that if I write a class, I can definite a custom print function as below. ``` >>> class F: ... def __str__(self): ... return 'This describes the data of F.' ... >>> f = F() >>> print f This describes the data of F. ``` But, what if I want to do the same for a function object? For example, ``` >>> def f(): ... pass ... >>> g = f >>> print g <function f at 0x7f738d6da5f0> ``` Instead of '<function f at 0x7f738d6da5f0>', I'd like to somehow specify what was printed. The motivation for doing this is that I'm going to store a bunch of function objects in a list, and I'd like to iterate over the list and print human-readable descriptions of the types of functions without adding additional complexity, e.g., tuples of function objects and strings. Thanks in advance for any help you can provide. Edit: I changed my example to reflect what I was trying to convey, unfortunately I typed 'f()' when I meant 'f'. I am interested in a custom label for the function object, not customizing the return (which it is obvious how to do). Sorry for any confusion this has caused.