简体   繁体   English

如果没有在Python中导入,全局命名空间中的内置模块的内容如何可用?

[英]How are the contents of the builtins module available in the global namespace without import in Python?

I've been using Python for a good period of time. 我一直在使用Python很长一段时间。 I have never found out how built-in functions work. 我从来没有发现内置函数是如何工作的。 In different words, how are they included without having any module imported to use them? 换句话说,如果没有导入任何模块来使用它们,它们是如何被包含的? What if I want to add to them (locally)? 如果我想添加(本地)怎么办?

This may seem naive. 这可能看起来很幼稚。 But, I haven't really found any answer that explains comprehensively how do we have built-in functions, global variables, etc., available to us when developing a script. 但是,我还没有真正找到任何答案,全面解释我们在开发脚本时如何使用内置函数,全局变量等。

In a nutshell, where do we include the builtins module? 简而言之,我们在哪里包含内置模块?

I have encountered this question . 我遇到过这个问题 But it gives a partial answer to my question. 但它给出了我的问题的部分答案。

The not-implementation-details part of the answer is that the builtins module, or __builtin__ in Python 2, provides access to the built-ins namespace. 答案的非实现细节部分是builtins模块,或Python 2中的__builtin__ ,提供对内置命名空间的访问。 If you want to modify the built-ins (you usually shouldn't), setting attributes on builtins is how you'd go about it. 如果你想修改内置插件(你通常不应该这样做),在builtins设置上设置属性是你如何去做的。

The implementation details part of the answer is that Python keeps track of built-ins in multiple ways. 实现细节部分答案是Python以多种方式跟踪内置函数。 For example, each frame object keeps track of the built-in namespace it's using, which may be different from other frames' built-in namespaces. 例如,每个框架对象都会跟踪它正在使用的内置命名空间,这可能与其他框架的内置命名空间不同。 You can access this through a frame's f_builtins attribute. 您可以通过框架的f_builtins属性访问它。 When a LOAD_GLOBAL instruction fails to find a name in the frame's globals, it looks in the frame's builtins. LOAD_GLOBAL指令无法在框架的全局变量中找到名称时,它会查看框架的内部结构。 There's also a __builtins__ global variable in most global namespaces, but it's not directly used for built-in variable lookup; 在大多数全局命名空间中还有一个__builtins__全局变量,但它并不直接用于内置变量查找; instead, it's used to initialize f_builtins in certain situations during frame object creation. 相反,它用于在帧对象创建期间在某些情况下初始化f_builtins There's also a builtins reference in the global PyInterpreterState , which is used as default builtins if there's no current frame object. 全局PyInterpreterState还有一个builtins引用,如果没有当前帧对象,它将用作默认内置函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM