【问题标题】:Can Python print a function definition?Python可以打印函数定义吗?
【发布时间】:2009-10-13 20:33:35
【问题描述】:

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

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

【问题讨论】:

  • 你有函数的来源。这有什么问题?
  • 在交互模式下,您可以使用 help(function) 显示函数的文档字符串。
  • 这个问题有一个重复:stackoverflow.com/questions/427453/…
  • @S.Lott 如果有好的方法。例如,初学者可以打印一个装饰函数并轻松查看更改。

标签: python


【解决方案1】:

如果是导入函数,可以使用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 文件等上)

【讨论】:

  • 运行时创建的函数(包括交互式提示)也没有文件或行号,这是有道理的
  • 这似乎就是我想要的。谢谢!
  • 打印一个我之前在当前交互式 Python 解释器中定义的函数定义怎么样?这可能吗?
  • @GL2014:是的,看我的回答。
  • 我可以确认这个答案和 inspect.getsource() DOES 可以在 Python 3.6.9 (Ubuntu) 中使用交互式 (ipython3) 定义的函数。
【解决方案2】:

如果您使用的是iPython,您可以使用function_name? 来获取帮助,如果可以的话,function_name?? 会打印出来源。

【讨论】:

  • 有时你需要将函数分离到另一行来调用?例如模型.功能??不起作用,但 f = model.function; F??作品
【解决方案3】:

这就是我想出的方法:

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

这会取出换行符并将函数很好地打印出来

【讨论】:

  • 那里的破例,应该是 i.getsource(MyFunction)。
【解决方案4】:

虽然我通常同意inspect 是一个很好的答案,但我不同意您无法获得解释器中定义的对象的源代码。如果您使用dill 中的dill.source.getsource,您可以获得函数和lambda 的来源,即使它们是交互定义的。 它还可以从 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

>>> 

【讨论】:

  • 有时它不能直接使用:getsource(my_function),但是我可以让它使用 getsource(my_function.func_code)
【解决方案5】:

您可以使用 __doc__ 关键字:

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

【讨论】:

  • 这是描述,不是定义。
  • 对于许多内置函数(通常是在 C 模块中定义的函数),它也包括函数签名,但一般不包括。
  • 在交互式 shell 中,"help(object)" 将以更易于导航的方式显示。
  • @kaizer 函数签名也不是定义。 __doc__ 实际上 返回的是代码作者放入文档字符串(三引号字符串)中的任何内容。不多也不少。
  • 我认为这里的定义是模棱两可的。对我来说,它可能意味着文档字符串或代码文本或两者,甚至是代码对象。
【解决方案6】:

使用help(function)获取功能描述。

你可以阅读更多关于help()here的信息。

【讨论】:

  • 在我的帮助中没有定义源代码。
【解决方案7】:

可以在函数中使用__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.

【讨论】:

  • 问题是关于函数定义而不是函数文档字符串。
猜你喜欢
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 2019-10-21
  • 2018-03-22
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多