Python 可以打印函数定义吗?

在 JavaScript 中,可以打印出函数的定义。有没有在 Python 中实现这一点的方法?

(只是在交互模式下玩玩,我想读一个没有 open ()的模块,我只是好奇)。

108788 次浏览

如果使用 IPython,可以使用 function_name?获得帮助,如果可以的话,function_name??将打印出源代码。

如果要导入函数,可以使用 inspect.getsource:

>>> import re
>>> import inspect
>>> print inspect.getsource(re.compile)
def compile(pattern, flags=0):
"Compile a regular expression pattern, returning a pattern object."
return _compile(pattern, flags)

这个 威尔可以在交互式提示符中工作,但显然只能在导入的对象上工作(而不是在交互式提示符中定义的对象)。当然,它只有在 Python 能够找到源代码的情况下才能工作(所以不能在内置对象 C libs 上找到源代码)。Pyc 文件等)

可以使用 _ _ doc _ _ 关键字:

#print the class description
print string.__doc__
#print function description
print open.__doc__

虽然我一般同意 inspect是一个很好的答案,但是我不同意你不能得到解释器中定义的对象的源代码。如果使用 dill中的 dill.source.getsource,即使它们是交互定义的,也可以获得函数和 lambdas 的源代码。 它还可以从在 curries 中定义的绑定或未绑定类方法和函数中获得代码... ... 然而,如果没有封闭对象的代码,您可能无法编译该代码。

>>> from dill.source import getsource
>>>
>>> def add(x,y):
...   return x+y
...
>>> squared = lambda x:x**2
>>>
>>> print getsource(add)
def add(x,y):
return x+y


>>> print getsource(squared)
squared = lambda x:x**2


>>>
>>> class Foo(object):
...   def bar(self, x):
...     return x*x+x
...
>>> f = Foo()
>>>
>>> print getsource(f.bar)
def bar(self, x):
return x*x+x


>>>

你可以在函数中使用 __doc__,以 hog()函数为例: 您可以看到 hog()的用法如下:

from skimage.feature import hog


print hog.__doc__

产出将是:

Extract Histogram of Oriented Gradients (HOG) for a given image.
Compute a Histogram of Oriented Gradients (HOG) by


1. (optional) global image normalisation
2. computing the gradient image in x and y
3. computing gradient histograms
4. normalising across blocks
5. flattening into a feature vector


Parameters
----------
image : (M, N) ndarray
Input image (greyscale).
orientations : int
Number of orientation bins.
pixels_per_cell : 2 tuple (int, int)
Size (in pixels) of a cell.
cells_per_block  : 2 tuple (int,int)
Number of cells in each block.
visualise : bool, optional
Also return an image of the HOG.
transform_sqrt : bool, optional
Apply power law compression to normalise the image before
processing. DO NOT use this if the image contains negative
values. Also see `notes` section below.
feature_vector : bool, optional
Return the data as a feature vector by calling .ravel() on the result
just before returning.
normalise : bool, deprecated
The parameter is deprecated. Use `transform_sqrt` for power law
compression. `normalise` has been deprecated.


Returns
-------
newarr : ndarray
HOG for the image as a 1D (flattened) array.
hog_image : ndarray (if visualise=True)
A visualisation of the HOG image.


References
----------
* http://en.wikipedia.org/wiki/Histogram_of_oriented_gradients


* Dalal, N and Triggs, B, Histograms of Oriented Gradients for
Human Detection, IEEE Computer Society Conference on Computer
Vision and Pattern Recognition 2005 San Diego, CA, USA


Notes
-----
Power law compression, also known as Gamma correction, is used to reduce
the effects of shadowing and illumination variations. The compression makes
the dark regions lighter. When the kwarg `transform_sqrt` is set to
``True``, the function computes the square root of each color channel
and then applies the hog algorithm to the image.

这是我想出来的方法:

    import inspect as i
import sys
sys.stdout.write(i.getsource(MyFunction))

这会取出新的行字符并很好地打印出函数

使用 help(function)获取函数描述。

你可以阅读更多关于 help() 给你的资料。

如果要导入函数,可以使用 spect.getsource。这将在交互式提示符中起作用,但显然只能在导入的对象(而不是在交互式提示符中定义的对象)上起作用

它也不适用于许多类型的动态执行代码,比如 exec()。在 Python v3.3 + 中,可以使用 inspect.signature()。它表明这也是 help()在内部使用的。这也适用于交互式定义的事物。

例如:

import inspect


code = """
def sum(a:int, b:int=5) -> int:
return a + b
"""


exec(code)
print(sum(2))
print("def sum{}".format(inspect.signature(sum)))

结果是:

7
def sum(a: int, b: int = 5) -> int

旁注: 是的,exec()是危险的。如果你不知道为什么,你就不该用它。这里纯粹是用来演示的。

我知道这个问题很老套,但我只是想澄清一些事情。

我在谷歌上搜索了这个问题的解决方案,发现了这个问题,我发现在 IPython 中可以使用 inspect.getsource来获取解释器中定义的函数。

但是您不能使用它来获取在普通 Python shell (即 Python.exe)中交互定义的函数的定义。

Python 3.10.5上的 IPython 8.4.0

Python 3.10.5 (tags/v3.10.5:f377153, Jun  6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type 'copyright', 'credits' or 'license' for more information
IPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.


In [1]: import inspect
...: def fibonacci(n):
...:     s = []
...:     a, b = 0, 1
...:     for i in range(n):
...:         s.append(a)
...:         a, b = b, a + b
...:     return s
...:
...: fibonacci(16)
Out[1]: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]


In [2]: print(inspect.getsource(fibonacci))
def fibonacci(n):
s = []
a, b = 0, 1
for i in range(n):
s.append(a)
a, b = b, a + b
return s

Python 3.10.5

Python 3.10.5 (tags/v3.10.5:f377153, Jun  6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import inspect
>>> def fibonacci(n):
...     s = []
...     a, b = 0, 1
...     for i in range(n):
...         s.append(a)
...         a, b = b, a + b
...     return s
...
>>> fibonacci(16)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
>>> print(inspect.getsource(fibonacci))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Python310\lib\inspect.py", line 1147, in getsource
lines, lnum = getsourcelines(object)
File "C:\Program Files\Python310\lib\inspect.py", line 1129, in getsourcelines
lines, lnum = findsource(object)
File "C:\Program Files\Python310\lib\inspect.py", line 958, in findsource
raise OSError('could not get source code')
OSError: could not get source code