Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 490
ndrwnaguib Avatar asked Jan 13 '19 22:01

ndrwnaguib


1 Answers

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.

like image 95
user2357112 supports Monica Avatar answered Sep 21 '22 21:09

user2357112 supports Monica