programing

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

jooyons 2023. 7. 19. 21:20
반응형

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

자바스크립트에서는 함수의 정의를 출력할 수 있습니다.파이썬에서 이를 달성할 수 있는 방법이 있습니까?

(인터랙티브 모드에서 놀고 있을 뿐이고, 오픈() 없이 모듈을 읽고 싶었습니다.그냥 궁금해서요).

함수를 가져오는 경우 다음을 사용할 수 있습니다.

>>> 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이 소스 코드를 찾을 수 있는 경우에만 작동합니다(따라서 기본 제공 개체, Clibs, .pyc 파일 등에서는 작동하지 않습니다).

iPython을 사용하는 경우 를 사용하여 도움을 받을 수 있으며 가능하면 소스를 출력합니다.

제가 알아낸 방법은 다음과 같습니다.

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

이것은 새로운 라인 문자를 제거하고 기능을 멋지게 출력합니다.

저도 동의하지만,inspect좋은 답변입니다. 인터프리터에 정의된 객체의 소스 코드를 얻을 수 없다는 것에 동의하지 않습니다.사용하는 경우dill.source.getsource에서 함수와 람다의 소스를 얻을 수 있습니다. 대화식으로 정의된 경우에도 마찬가지입니다.또한 curry에 정의된 frombound 또는 bound 클래스 메서드 및 함수에 대한 코드를 가져올 수 있습니다.그러나 동봉된 개체의 코드 없이는 해당 코드를 컴파일할 수 없습니다.

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

>>> 

사용하다help(function)함수 설명을 가져옵니다.

자세한 내용은 다음을 참조하십시오.help() 여기에

이 질문이 오래된 질문인 것은 알지만, 몇 가지만 명확히 하고 싶었습니다.

저는 해서 이했는데, 에서 나는문제대해검이발질견문했을고, 당신사수 IPthon다찾을 할 수 했습니다.inspect.getsource인터프리터에 정의된 함수를 가져옵니다.

수는 그나일 반셸에 Python 대형정로의함으된다없니습수수정가의데사져용할오는러를의화서▁defined▁but다없니습i▁defin▁to수▁(▁it▁get▁the'▁of▁interactitions▁you▁uset러그▁python▁can▁functions▁plain).Python.exe).

Python 3.10.5의 IPython 8.4.0

Python 3.10.5 (tags/v3.10.5:f377153, Jun  6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type 'copyright', 'credits' or 'license' for more information
IPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import inspect
   ...: def fibonacci(n):
   ...:     s = []
   ...:     a, b = 0, 1
   ...:     for i in range(n):
   ...:         s.append(a)
   ...:         a, b = b, a + b
   ...:     return s
   ...:
   ...: fibonacci(16)
Out[1]: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

In [2]: print(inspect.getsource(fibonacci))
def fibonacci(n):
    s = []
    a, b = 0, 1
    for i in range(n):
        s.append(a)
        a, b = b, a + b
    return s

파이썬 3.10.5

Python 3.10.5 (tags/v3.10.5:f377153, Jun  6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import inspect
>>> def fibonacci(n):
...     s = []
...     a, b = 0, 1
...     for i in range(n):
...         s.append(a)
...         a, b = b, a + b
...     return s
...
>>> fibonacci(16)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
>>> print(inspect.getsource(fibonacci))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\Python310\lib\inspect.py", line 1147, in getsource
    lines, lnum = getsourcelines(object)
  File "C:\Program Files\Python310\lib\inspect.py", line 1129, in getsourcelines
    lines, lnum = findsource(object)
  File "C:\Program Files\Python310\lib\inspect.py", line 958, in findsource
    raise OSError('could not get source code')
OSError: could not get source code

함수를 가져오는 경우 inspect.get source를 사용할 수 있습니다.이 작업은 대화형 프롬프트에서 작동하지만, 분명히 가져온 개체(대화형 프롬프트 내에서 정의된 개체가 아님)에만 적용됩니다.

또한 다음과 같이 동적으로 실행되는 여러 유형의 코드에서는 작동하지 않습니다.exec()Python 에서는 Python v3.3을 할 수 .+에서는inspect.signature()이런 것 같습니다.help()내부적으로도 사용합니다.이것은 또한 대화형으로 정의된 것들과도 작동합니다.

예:

import inspect

code = """
def sum(a:int, b:int=5) -> int:
  return a + b
"""

exec(code)
print(sum(2))
print("def sum{}".format(inspect.signature(sum)))

그 결과:

7
def sum(a: int, b: int = 5) -> int

참고 사항:네.exec()위험합니다.이유를 모른다면, 그것을 사용하지 말아야 합니다.여기서는 순전히 시연용으로 사용됩니다.

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

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

사용할 수 있습니다.__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.

언급URL : https://stackoverflow.com/questions/1562759/can-python-print-a-function-definition

반응형