Why does the globals()['__builtins__'] type change when being imported? Does Python create a new __builtins__ object for each module?

Viewed 25

Let's say we have some module A with the following code:

# A

foo = globals()['__builtins__']

print(foo)
print(type(foo))

Running it gives the output:

<module 'builtins' (built-in)>
<class 'module'>

However, if we import module A into another module B:

# B

import A

The following is printed:

{'__name__': 'A', '__doc__': None, '__package__': '', '__loader__': <_frozen_importlib ...
<class 'dict'>

So our 'builtins' module turns into a dictionary, while all the other elements of globals() stay the same. Would be interesting to understand the machinery behind this.

0 Answers
Related