I’m scripting using Python in Blender, a 3D graphics tool. I initially intended to post this topic on the blender stack exchange, but I’ve come to the conclusion that it’s closer to the basics of Python, which led me to write the question here. Please let me know if I’m on the wrong forum!
I made the mistake of using the default function name as a variable name in Python some time ago, like list = ['a', 'b', 'c', 'd']
. To take the more extreme case, all the print functions in my code would not have worked if I had declared a variable like print = 'a'
.
So I tried to write a code that prints out all the variable names that are already reserved. Even if I wanted to use list
or print
as the variable names, I would use a different name because I saw True
returned and knew that this was already using these names in __builtins__
. Now that I’ve tested it in the Python console, I went to a text editor and ran the same code, but this time I got False
instead of True
. What happened?
I used the dir()
function to check the values actually inside __builtins__
. The output from the Python console contained print
and list
in __builtins__
as expected, but the output from the text editor had different values. Upon closer inspection, I noticed that there were values such as keys
, items
, values
, which are methods available on the dictionary!
This time, I used the type()
function to print the type of __builtins__
. The Python console printed <class 'module'>
and the text editor printed <class 'dict'>
.
I know that Blender’s python console and text editor work separately within different scopes, but I don’t know what’s going on specifically. Why is the output different for __builtins__
?
Advertisement
Answer
You’re using different implementations of Python, and the value of __builtins__
is deliberately left underspecified in the docs.
As an implementation detail, most modules have the name
__builtins__
made available as part of their globals. The value of__builtins__
is normally either this module or the value of this module’s__dict__
attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.
So __builtins__
is simply a convenience mechanism for particular implementations and is generally set to either builtins
or builtins.__dict__
. It looks like your Python console does the former and Blender’s version does the latter. To do it in a uniform way across implementations, you can do
import builtins print(type(builtins)) # <class 'module'> print(type(builtins.__dict__)) # <class 'dict'>