파이썬이 함수 정의를 인쇄 할 수 있습니까?


112

JavaScript에서는 함수의 정의를 인쇄 할 수 있습니다. 파이썬에서 이것을 수행하는 방법이 있습니까?

(대화 형 모드에서 놀았고 open ()없이 모듈을 읽고 싶었습니다. 그냥 궁금했습니다.)


기능에 대한 소스가 있습니다. 그게 무슨 문제입니까?
S.Lott

1
대화 형 모드에서 help (function)을 사용하여 함수에 대한 독 스트링을 표시 할 수 있습니다.
monkut 09

이 질문의 중복이 있습니다 : stackoverflow.com/questions/427453/…
Anderson Green

답변:


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 libs, .pyc 파일 등에서는 제외).


의미가 파일 또는 중 하나 LINENUMBER,이없는 (대화 형 프롬프트 포함) 런타임에 생성 기능
존 라 Rooy

그게 제가 찾던 것 같습니다. 감사!
Eddie Welker

9
현재 대화 형 Python 인터프리터에서 이전에 정의한 함수 정의를 인쇄하는 것은 어떻습니까? 이게 가능해?
GL2014

@ GL2014 : 예, 내 대답을 참조하십시오.
Mike McKerns

나는이 대답과 inspect.getsource ()을 확인할 수 있습니다 합니까 파이썬 3.6.9 (우분투)에서 대화 형 (ipython3)에 작업 정의 funciton를.
Gnudiff

97

iPython을 사용하는 경우을 사용 function_name?하여 도움을받을 수 function_name??있으며 가능한 경우 소스를 인쇄합니다.


2
때로는 함수를 다른 줄로 분리하여 호출해야합니까? 예 : model.function ?? 작동하지 않지만 f = model.function; 에프?? 작동
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하면 대화 형으로 정의 된 경우에도 함수 및 람다의 소스를 가져올 수 있습니다. 또한 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

>>> 

1
: 때로는 직접 작동하지 않습니다 getSource와 (my_function) ,하지만 그때와 함께 작동하도록 그것을 얻을 수있다 (my_function.func_code) getSource와
영감

2

help(function)함수 설명을 가져 오는 데 사용 합니다.

help() 여기에서 자세한 내용을 읽을 수 있습니다 .


1
나를 위해 도움말에 정의 된 소스가 없습니다.
ansuman

-6

__doc__ 키워드를 사용할 수 있습니다.

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

1
그것은 정의가 아니라 설명입니다.
Triptych

많은 내장 (일반적으로 C 모듈에 정의 된 함수)의 경우 함수 서명도 포함되지만 일반적으로 포함되지는 않습니다.
u0b34a0f6ae

1
대화 형 셸에서 "help (object)"는이를보다 탐색 가능한 방식으로 표시합니다.
TK.

@kaizer 함수 서명도 정의가 아닙니다. 무엇 __doc__ 실제로 반환하면 문서화 문자열에서 코드를 넣어 (트리플 인용 문자열)의 어떤 저자이다. 그 이상도 그 이하도 아닙니다.
Triptych

여기서 정의가 모호하다고 생각합니다. 나에게 그것은 독 스트링이나 코드 텍스트 또는 둘 다 또는 심지어 코드 객체를 의미 할 수 있습니다
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
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.