Pythonは関数定義を出力できますか?


112

JavaScriptでは、関数の定義を出力できます。Pythonでこれを実現する方法はありますか?

(対話モードで遊んでいるだけで、open()なしでモジュールを読みたかったのです。私は興味がありました)。


関数のソースがあります。それの何がいけないの?
S.Lott、2009年

1
インタラクティブモードから、help(function)を使用して、関数のdocstringを表示できます。
monkut、2009年

回答:


157

関数をインポートする場合は、以下を使用できます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ファイルなどではできません)。


実行時に作成される関数(インタラクティブプロンプトを含む)にもファイルまたは
行番号

それが私が探していたもののようです。ありがとう!
Eddie Welker、

9
現在の対話型Pythonインタープリターで以前に定義した関数定義を印刷するのはどうですか?これは可能ですか?
GL2014、2015年

@ GL2014:はい​​、私の答えをご覧ください。
マイクマッカーンズ2016

私はこの答えとinspect.getsource()があることを確認することができますDOESのPython 3.6.9(Ubuntuの)でインタラクティブ(ipython3)の作業定義されたfuncitonを。
グヌーディフ

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、関数とラムダがインタラクティブに定義されている場合でも、それらのソースを取得できます。また、カレーで定義されているバインド済みまたはバインドなしのクラスメソッドおよび関数からコードを取得することもできます。ただし、オブジェクトを囲むコードがないと、そのコードをコンパイルできない場合があります。

>>> 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)
霊感


-6

__doc__キーワードを使用できます。

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

1
それは説明ではなく、定義です。
トリプティク

多くの組み込み関数(原則として、Cモジュールで定義された関数)では、関数シグネチャも含まれますが、一般的には含まれていません。
u0b34a0f6ae 2009年

1
対話型シェルでは、「help(object)」はこれをよりナビゲート可能な方法で表示します。
TK。

@kaizer関数シグネチャも定義ではありません。どのような__doc__ 実際に返すことはドキュメンテーション文字列内のコードプット(トリプル引用符で囲まれた文字列)のどんな著者です。それ以上でもそれ以下でもありません。
トリプティク

ここでは定義があいまいだと思います。私にとっては、docstring、コードテキスト、またはその両方、あるいはコードオブジェクトさえも一気に意味するかもしれません
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 2017年
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.