简体   繁体   中英

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. 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. If you want to modify the built-ins (you usually shouldn't), setting attributes on builtins is how you'd go about it.

The implementation details part of the answer is that Python keeps track of built-ins in multiple ways. 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. When a LOAD_GLOBAL instruction fails to find a name in the frame's globals, it looks in the frame's builtins. There's also a __builtins__ global variable in most global namespaces, but it's not directly used for built-in variable lookup; instead, it's used to initialize f_builtins in certain situations during frame object creation. There's also a builtins reference in the global PyInterpreterState , which is used as default builtins if there's no current frame object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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