For example, in REPL:
In [0]: def func(x=0, y=1):
...: return x
In [1]: func
Out [1]: <function __main__.func(x=0, y=1)>
But how do I print it or store in a variable?
In [2]: print(func)
Out [2]:
<function func at 0x000002182B32F5E0>
In [3]: str(func)
Out [3]: <function func at 0x000002182B32F5E0>
In [4]: repr(func)
Out [4]: <function func at 0x000002182B32F5E0>
One way would be to:
In [5]: string = eval('func')
In [6]: print(string)
Out [6]:
<function __main__.func(x=0, y=1)>
But this does not look safe, and even if it is, I want to know what method of the function generates this. For example str
invokes internal __str__
or repr
invokes internal __repr__
. Or is it just eval
formatting this?
As a workaround, I can do:
In [7]: from inspect import signature
In [8]: sign = str(signature(d)).strip('<Signature />')
In [9]: string = f"<{func.__class__.__name__} {func.__module__}.{func.__name__}{sign}>"
In [10]: print(string)
Out [10]:
<function __main__.func(x=0, y=1)>
This works, but it seems like I am doing work that's already been done, and I am reluctant to use eval
. Is there any other way I can get this? It seems like I am missing something very simple.
NOTE: Version: IPython 3.8.5