Python可以打印函数定义吗?


111

在JavaScript中,可以打印出函数的定义。有没有办法在Python中完成此任务?

(只是在交互模式下玩,所以我想在没有open()的情况下读取模块。我只是很好奇。)


您具有该功能的来源。怎么了
S.Lott

1
在交互模式下,您可以使用help(function)显示该函数的文档字符串。
09年

Answers:


156

如果要导入功能,则可以使用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库,.pyc文件等上找到)


在运行时创建的函数(包括交互式提示)也没有文件或行号,这很有意义
John La Rooy

那似乎是我想要的。谢谢!
Eddie Welker

9
如何打印我在当前的交互式Python解释器中先前定义的函数定义?这可能吗?
GL2014年

@ GL2014:是的,请参阅我的答案。
Mike McKerns 2016年

我可以确认此答案和inspect.getsource()确实适用于Python 3.6.9(Ubuntu)中的交互式(ipython3)定义的函数。
格努迪夫

97

如果您使用的是iPython,则可以使用function_name?获得帮助,并且function_name??可以打印出源代码。


2
有时您需要将函数分成另一行来调用?例如model.function?不起作用,但是f = model.function; F??作品
thecheech

12

这是我想出的方法:

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

这样可以取出换行符并很好地打印功能


1
此处的示例不完整,应该是i.getsource(MyFunction)。
svth

10

尽管我通常会认为这inspect是一个很好的答案,但我不同意您无法获得解释器中定义的对象的源代码。如果使用dill.source.getsourcefrom dill,即使它们是交互式定义的,也可以获取函数和lambda的来源。它也可以从咖喱中定义的绑定或未绑定类方法和函数中获取代码。但是,如果没有封闭对象的代码,则可能无法编译该代码。

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

>>> 

1
有时它不能直接用于:getsource(my_function),但是然后我可以将其与getsource(my_function.func_code)一起使用
Afflatus

2

help(function)得到的功能说明。

您可以help() 在此处了解更多信息。


1
没有为我定义帮助的来源。
ansuman

-6

您可以使用__doc__关键字:

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

1
那是描述,而不是定义。
三联画

对于许多内置函数(通常是C模块中定义的函数),它也包含函数签名,但通常不包含。
u0b34a0f6ae

1
在交互式外壳中,“ help(object)”将以更易于浏览的方式显示此内容。
传统知识。

@kaizer函数签名也不是定义。什么__doc__ 实际返回的代码放在文档字符串(三重引号的字符串)的作者不管。仅此而已。
三联画

我认为这里的定义不明确。对我来说,这可能意味着文档字符串或代码文本或两者兼而有之甚至是代码对象
John La Rooy

-6

您可以__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.

1
问题是关于函数定义而不是函数文档字符串。
ctrl-alt-delor
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.