查找内置Python函数的源代码?

查找内置Python函数的源代码?,python,python-internals,Python,Python Internals,有没有办法了解python中内置函数的工作方式?我的意思不仅仅是如何使用它们,还包括它们是如何构建的,排序后的代码是什么,或者枚举后的代码是什么等等?由于Python是开源的,所以您可以阅读 要了解特定模块或函数在哪个文件中实现,通常可以打印\uuuu file\uuu属性。或者,您可以使用inspect模块,请参阅inspect文档中的部分 对于内置类和方法,这并不是那么简单,因为inspect.getfile和inspect.getsource将返回一个类型错误,说明对象是内置的。但是,可以

有没有办法了解python中内置函数的工作方式?我的意思不仅仅是如何使用它们,还包括它们是如何构建的,排序后的代码是什么,或者枚举后的代码是什么等等?

由于Python是开源的,所以您可以阅读

要了解特定模块或函数在哪个文件中实现,通常可以打印
\uuuu file\uuu
属性。或者,您可以使用
inspect
模块,请参阅
inspect
文档中的部分

对于内置类和方法,这并不是那么简单,因为
inspect.getfile
inspect.getsource
将返回一个类型错误,说明对象是内置的。但是,可以在中找到许多内置类型。例如,有关enumerate类的实现或
列表
类型的实现,请参见。

shell简化了这一过程:
函数?
将为您提供文档<代码>功能???也显示代码。但这只适用于纯python函数

然后,您可以随时获取(c)Python的源代码


如果您对核心功能的pythonic实现感兴趣,请查看源代码。

这里有一个菜谱答案作为补充,CPython已迁移到GitHub,Mercurial存储库将不再更新:

  • 如有必要,安装Git
  • git克隆https://github.com/python/cpython.git

  • 代码将签出到名为cpython->cd cpython

  • 假设我们正在寻找
    print()
    的定义
  • egrep--color=always-R'print'| less-R
  • 啊哈!请参见
    Python/bltinmodule.c
    ->
    builtin\u print()
  • 享受。

    2种方法

  • 您可以使用
    help()
  • 您可以使用
    inspect
  • 1)检查:

    使用insect模块浏览您想要的代码。。。 注意:您只能浏览已导入的模块(aka)包的代码

    例如:

      >>> 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  --
    
    >帮助(str)
    关于模块_u内置中的类str的帮助:
    类str(基串)
    |str(对象=“”)->string
    |
    |返回对象的良好字符串表示形式。
    |如果参数是字符串,则返回值是相同的对象。
    |
    |方法解析顺序:
    |str
    |基线
    |反对
    |
    |此处定义的方法:
    |
    |添加(…)
    |x.uu添加_uu(y)x+y
    |
    |_uuu包含uuuu(…)
    |x.uuu在x中包含_uuu(y)y
    |
    |_uuueq_uuuu(…)
    |x.。uuu eq_uuu(y)x==y
    |
    |格式
    |S.。\uuuu格式\uuuu(格式\u规范)->字符串
    |
    |按照format_spec的说明返回S的格式化版本。
    |
    |_uu_u_u_u_u(…)
    |x.uuu ge_uuu(y)x>=y
    |
    |_uuugetAttribute_uuuu(…)
    --更多--
    

    我不得不稍微挖掘一下以找到以下
    内置函数的源代码
    ,因为搜索将产生数千个结果。(祝你好运,搜索其中任何一个,找到它的来源)

    无论如何,所有这些函数都是在
    bltinmodule.c
    函数中定义的,函数以
    builtin{functionname}

    内置源代码:

    对于内置类型:


    Python是一个相当未知的资源


    在(某种程度上)最近的GH中,添加了一个新的章节来解决您提出的问题:。如果发生了变化,该资源也将得到更新。

    如@Jim所述,文件组织如下所述。复制以便于发现:

    对于Python模块,典型的布局是:

    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
    

    让我们直接回答你的问题

    查找内置Python函数的源代码?

    源代码位于
    cpython/Python/bltinmodule.c

    要在GitHub存储库中查找源代码,请转到。您可以看到,所有内置函数都以
    builtin\u
    开头,例如,
    sorted()
    builtin\u sorted
    中实现

    为方便起见,我将发布
    sorted()


    正如您可能已经注意到的,这不是Python代码,而是C代码。

    您能给出一个
    enumerate
    的示例吗?在OP之后,“sorted”的源代码如何?当然,inspect.getsourcefile(sorted)不起作用。@quetzalcatl
    sorted()
    的源代码在中,尽管它只是调用
    list.sort()
    ,所以如果您给出一个如何使用
    \uuuuuu文件的示例,对self和未来的谷歌用户来说是有帮助的:
    open()
    函数是在Python3的
    Modules/\u io/\u iomodule.c
    中定义的(而不是在其他内置函数中)。PyPy使用RPython作为大多数内置函数,其级别几乎可以与c一样低,也可以与Python一样高。通常介于两者之间。在这两种情况下,它都是静态类型的,因此它不是真正的Python。查看内置函数源代码的早期项目:OP特别想查看代码,帮助仅提供文档。列表是对象/类型,而不是内置函数。您可以在
    listobject.c
    dir
    中找到它的实现细节,因为它没有在c中实现,所以它不在该文件中。
    bltinmodule
    。啊,啊。他们为什么拼得这么糟糕?我尝试了一个快速的文件系统搜索
    builtin
    ,但什么都没有找到!
    builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
    {
        PyObject *newlist, *v, *seq, *callable;
    
        /* Keyword arguments are passed through list.sort() which will check
           them. */
        if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
            return NULL;
    
        newlist = PySequence_List(seq);
        if (newlist == NULL)
            return NULL;
    
        callable = _PyObject_GetAttrId(newlist, &PyId_sort);
        if (callable == NULL) {
            Py_DECREF(newlist);
            return NULL;
        }
    
        assert(nargs >= 1);
        v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
        Py_DECREF(callable);
        if (v == NULL) {
            Py_DECREF(newlist);
            return NULL;
        }
        Py_DECREF(v);
        return newlist;
    }