파이썬에서 내장 함수가 어떻게 작동하는지 볼 수있는 방법이 있습니까? 나는 그것들을 사용하는 방법뿐만 아니라 어떻게 만들어 졌는지, 정렬 되거나 열거 된 코드 등은 무엇입니까?
파이썬에서 내장 함수가 어떻게 작동하는지 볼 수있는 방법이 있습니까? 나는 그것들을 사용하는 방법뿐만 아니라 어떻게 만들어 졌는지, 정렬 되거나 열거 된 코드 등은 무엇입니까?
답변:
파이썬은 오픈 소스이기 때문에 소스 코드를 읽을 수 있습니다 .
특정 모듈이나 함수가 구현 된 파일을 찾으려면 일반적으로 __file__속성을 인쇄 할 수 있습니다 . 또는 inspect모듈을 사용할 수도 있습니다 . 의 문서에서 소스 코드 검색 섹션을 참조하십시오 inspect.
들어 내장 클래스와 방법이 그렇게하기 때문에 간단하지 않습니다 inspect.getfile및 inspect.getsource개체가 내장되어 있음을 알리는 유형의 오류를 반환합니다. 그러나 많은 기본 제공 유형은 ObjectsPython 소스 트렁크 의 하위 디렉토리 에서 찾을 수 있습니다 . 예를 들어, 참조 여기 열거 클래스의 구현을위한 또는 여기 의 구현을위한 list유형입니다.
sorted()는 /Python/bltinmodule.c에 있지만 list.sort()실제 소스는 /Objects/listobject.c에 있습니다.
다음은 @Chris ' 답변을 보완하는 요리 책 답변입니다 . CPython은 GitHub로 이동했으며 Mercurial 저장소는 더 이상 업데이트되지 않습니다.
git clone https://github.com/python/cpython.git
코드는 cpython-> 라는 서브 디렉토리로 체크 아웃됩니다.cd cpython
print()...egrep --color=always -R 'print' | less -RPython/bltinmodule.c->builtin_print()즐겨.
Built-in Functions검색 결과 수천 개의 결과를 얻을 수 있으므로 다음 소스를 찾기 위해 조금 파야했습니다 . (소스가있는 곳을 찾을 수있는 사람들을 검색하는 행운을 빕니다)
어쨌든, 모든 함수에 정의 된 bltinmodule.c기능으로 시작builtin_{functionname}
내장 소스 : https://github.com/python/cpython/blob/master/Python/bltinmodule.c
내장 유형 : https://github.com/python/cpython/tree/master/Objects
listobject.c github.com/python/cpython/tree/master/Objects
iPython 껍질이 쉽게 : function?당신에게 문서를 제공 할 것입니다.function??코드도 보여줍니다. 그러나 이것은 순수한 파이썬 함수에서만 작동합니다.
그런 다음 언제든지 (c) Python의 소스 코드를 다운로드 할 수 있습니다 .
핵심 기능의 파이썬 구현에 관심이 있다면 PyPy 소스를 살펴보십시오 .
2 가지 방법
help()inspect 1) 검사 :
inpsect 모듈을 사용 하여 원하는 코드를 탐색하십시오 ... 참고 : 가져온 모듈 (일명) 패키지에 대해서만 코드를 탐색 할 수 있습니다 .
예를 들어 :
>>> import randint
>>> from inspect import getsource
>>> getsource(randint) # here i am going to explore code for package called `randint`
2) 도움말 () :
당신은 단순히 사용할 수 있습니다 help()명령을 하여 내장 함수와 코드에 대한 도움말을 얻을 수 있습니다.
예를 들어 : str ()의 코드를 보려면-를 입력하십시오. help(str)
이렇게 반환됩니다
>>> help(str)
Help on class str in module __builtin__:
class str(basestring)
| str(object='') -> string
|
| Return a nice string representation of the object.
| If the argument is a string, the return value is the same object.
|
| Method resolution order:
| str
| basestring
| object
|
| Methods defined here:
|
| __add__(...)
| x.__add__(y) <==> x+y
|
| __contains__(...)
| x.__contains__(y) <==> y in x
|
| __eq__(...)
| x.__eq__(y) <==> x==y
|
| __format__(...)
| S.__format__(format_spec) -> string
|
| Return a formatted version of S as described by format_spec.
|
| __ge__(...)
| x.__ge__(y) <==> x>=y
|
| __getattribute__(...)
-- More --
잘 알려지지 않은 리소스는 Python Developer Guide 입니다.
최근의 GH 문제 에서 CPython Source Code Layout 이라는 새로운 질문이 추가되었습니다 . 변경해야 할 경우 해당 리소스도 업데이트됩니다.
@Jim이 언급했듯이 파일 구성은 여기 에 설명되어 있습니다 . 쉽게 발견 할 수 있도록 재현 :
파이썬 모듈의 경우 일반적인 레이아웃은 다음과 같습니다.
Lib/<module>.py Modules/_<module>.c (if there’s also a C accelerator module) Lib/test/test_<module>.py Doc/library/<module>.rst확장 전용 모듈의 경우 일반적인 레이아웃은 다음과 같습니다.
Modules/<module>module.c Lib/test/test_<module>.py Doc/library/<module>.rst내장 유형의 일반적인 레이아웃은 다음과 같습니다.
Objects/<builtin>object.c Lib/test/test_<builtin>.py Doc/library/stdtypes.rst내장 함수의 경우 일반적인 레이아웃은 다음과 같습니다.
Python/bltinmodule.c Lib/test/test_builtin.py Doc/library/functions.rst일부 예외 :
builtin type int is at Objects/longobject.c builtin type str is at Objects/unicodeobject.c builtin module sys is at Python/sysmodule.c builtin module marshal is at Python/marshal.c Windows-only module winreg is at PC/winreg.c
enumerate?