IT story

내장 파이썬 함수의 소스 코드를 찾으십니까?

hot-time 2020. 8. 2. 17:17
반응형

내장 파이썬 함수의 소스 코드를 찾으십니까?


파이썬에서 내장 함수가 어떻게 작동하는지 볼 수있는 방법이 있습니까? 나는 그것들을 사용하는 방법뿐만 아니라 어떻게 만들어 졌는지, 정렬 되거나 열거 코드 등은 무엇입니까?


파이썬은 오픈 소스이므로 소스 코드를 읽을 수 있습니다 .

특정 모듈이나 함수가 구현 된 파일을 찾으려면 일반적으로 __file__속성을 인쇄 할 수 있습니다 . 또는 inspect모듈을 사용할 수도 있습니다 . 의 문서에서 소스 코드 검색 섹션을 참조하십시오 inspect.

들어 내장 클래스와 방법이 그렇게하기 때문에 간단하지 않습니다 inspect.getfileinspect.getsource개체가 내장되어 있음을 알리는 유형의 오류를 반환합니다. 그러나 많은 기본 제공 유형은 ObjectsPython 소스 트렁크하위 디렉토리 에서 찾을 수 있습니다 . 예를 들어, 참조 여기 열거 클래스의 구현을위한 또는 여기 의 구현을위한 list유형입니다.


다음은 @Chris ' 답변을 보충하는 요리 책 답변입니다 . CPython은 GitHub로 이동했으며 Mercurial 저장소는 더 이상 업데이트되지 않습니다.

  1. 필요한 경우 Git을 설치하십시오.
  2. git clone https://github.com/python/cpython.git

  3. 코드는 cpython-> 라는 서브 디렉토리로 체크 아웃됩니다.cd cpython

  4. 우리가 정의를 찾고 있다고 가정 해 봅시다 print()...
  5. egrep --color=always -R 'print' | less -R
  6. 아하! 참조 Python/bltinmodule.c->builtin_print()

즐겨.


iPython 껍질이 쉽게 : function?당신에게 문서를 제공 할 것입니다. function??코드도 보여줍니다. 그러나 이것은 순수한 파이썬 함수에서만 작동합니다.

그런 다음 언제든지 (c) Python의 소스 코드를 다운로드 할 수 있습니다 .

핵심 기능의 파이썬 구현에 관심이 있다면 PyPy 소스를 살펴보십시오 .


여기에 이미지 설명을 입력하십시오

Built-in Functions검색 결과 수천 개의 결과를 얻을 수 있으므로 다음 소스를 찾기 위해 조금 파야했습니다 . (소스가있는 곳을 찾을 수있는 사람들을 검색하는 행운을 빕니다)

어쨌든, 모든 함수에 정의 된 bltinmodule.c기능으로 시작builtin_{functionname}

내장 소스 : https://github.com/python/cpython/blob/master/Python/bltinmodule.c

For Built-in Types: https://github.com/python/cpython/tree/master/Objects


2 methods,

  1. You can check usage about snippet using help()
  2. you can check hidden code for those modules using inspect

1) inspect:

use inpsect module to explore code you want... NOTE: you can able to explore code only for modules (aka) packages you have imported

for eg:

  >>> import randint  
  >>> from inspect import getsource
  >>> getsource(randint) # here i am going to explore code for package called `randint`

2) help():

you can simply use help() command to get help about builtin functions as well its code.

for eg: if you want to see the code for str() , simply type - help(str)

it will return like this,

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

Quite an unknown resource is the 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

참고 URL : https://stackoverflow.com/questions/8608587/finding-the-source-code-for-built-in-python-functions

반응형