查找内置 Python 函数的源代码? [英] Finding the source code for built-in Python functions?

查看:48
本文介绍了查找内置 Python 函数的源代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法查看 Python 中的内置函数是如何工作的?我不是指如何使用它们,而是指它们是如何构建的,sortedenumerate 背后的代码是什么 等等...?

Is there a way to see how built in functions work in python? I don't mean just how to use them, but also how were they built, what is the code behind sorted or enumerate etc...?

推荐答案

由于 Python 是开源的,您可以阅读 源码代码.

Since Python is open source you can read the source code.

要找出特定模块或函数在哪个文件中实现,您通常可以打印 __file__ 属性.或者,您可以使用 inspect 模块,请参阅 inspect 文档中的noreferrer">Retrieving Source Code.

To find out what file a particular module or function is implemented in you can usually print the __file__ attribute. Alternatively, you may use the inspect module, see the section Retrieving Source Code in the documentation of inspect.

对于内置类和方法,这不是那么简单,因为 inspect.getfileinspect.getsource 将返回一个类型错误,说明对象是内置的.但是,许多内置类型可以在Objects Python 源码主干的子目录.例如,请参阅此处以了解枚举类的实现或这里用于list 输入.

For built-in classes and methods this is not so straightforward since inspect.getfile and inspect.getsource will return a type error stating that the object is built-in. However, many of the built-in types can be found in the Objects sub-directory of the Python source trunk. For example, see here for the implementation of the enumerate class or here for the implementation of the list type.

这篇关于查找内置 Python 函数的源代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆