IPython REPL中显示的函数表示在哪里/如何生成?

问题描述

例如,在REPL中:

In  [0]: def func(x=0,y=1):
    ...:     return x

In  [1]: func
Out [1]: <function __main__.func(x=0,y=1)>
@H_404_5@

但是如何打印它或将其存储在变量中?

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>
@H_404_5@

一种方法是:

In  [5]: string = eval('func')

In  [6]: print(string)

Out [6]: 
<function __main__.func(x=0,y=1)>
@H_404_5@

但是,这看起来并不安全,即使是这样,我也想知道该函数的哪种方法会产生这种情况。例如,str调用内部__str__repr调用内部__repr__。还是只是eval格式化它?

作为解决方法,我可以这样做:

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)>
@H_404_5@

方法有效,但似乎我正在完成已经完成的工作,因此我不愿意使用eval。我还有其他方法可以得到这个吗?似乎我缺少一些非常简单的东西。

注意: 版: IPython 3.8.5

enter image description here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)