在python中获取函数的字符串表示形式

时间:2018-12-27 09:45:26

标签: python

我已经看到了这个问题:

How can I get the source code of a Python function?

但是我找不到任何适用于内置函数和用户定义函数的东西。

例如,我尝试:

>>> print.__repr__()
'<built-in function print>'

>>> repr(print)
'<built-in function print>'

>>> print(print)
<built-in function print>

$ python
Python 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 18:10:19) 
>>> inspect.getsource(print)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/user/anaconda3/lib/python3.6/inspect.py", line 968, in getsource
    lines, lnum = getsourcelines(object)
  File "/home/user/anaconda3/lib/python3.6/inspect.py", line 955, in getsourcelines
    lines, lnum = findsource(object)
  File "/home/user/anaconda3/lib/python3.6/inspect.py", line 768, in findsource
    file = getsourcefile(object)
  File "/home/user/anaconda3/lib/python3.6/inspect.py", line 684, in getsourcefile
    filename = getfile(object)
  File "/home/user/anaconda3/lib/python3.6/inspect.py", line 666, in getfile
    'function, traceback, frame, or code object'.format(object))
TypeError: <built-in function print> is not a module, class, method, function, traceback, frame, or code object

我该怎么做?

更新:

重复警察:这不是重复。我显然是在逐字地引用并承认这个问题,它被认为是该问题第一行的重复,并要求对此进行扩展。

0 个答案:

没有答案