Подтвердить что ты не робот

Может ли Python распечатать определение функции?

В JavaScript можно распечатать определение функции. Есть ли способ сделать это в Python?

(Просто играю в интерактивном режиме, и я хотел прочитать модуль без open(). Мне было просто любопытно).

4b9b3361

Ответ 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 libs,.pyc файлах и т.д.)

Ответ 2

Если вы используете iPython, вы можете использовать function_name? для получения справки, и function_name?? будет распечатывать источник, если это возможно.

Ответ 3

Хотя я обычно соглашаюсь с тем, что inspect является хорошим ответом, я бы не согласился с тем, что вы не можете получить исходный код объектов, определенных в интерпретаторе. Если вы используете dill.source.getsource из dill, вы можете получить источник функций и лямбда, даже если они определены в интерактивном режиме. Он также может получить код для связанных или несвязанных методов и функций класса, определенных в карри... однако вы не сможете скомпилировать этот код без прилагаемого объектного кода.

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

>>> 

Ответ 4

Вот как я понял, как это сделать:

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

Это убирает символы новой строки и красиво выводит функцию

Ответ 5

Посмотрите на функцию help() из модуля pydoc. В интерактивном режиме он должен быть уже импортирован для вас, поэтому просто введите help(funtion_to_describe). Для получения дополнительных возможностей используйте IPython.

Ответ 6

Используйте help(function) чтобы получить описание функции.

Ответ 7

Вы можете использовать ключевое слово __doc__:

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

Ответ 8

Вы можете использовать __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.