Skip to content
Advertisement

The Python console and text editor output different output for __builtins__

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?

keyword in dir(builtins) in console

keyword in dir(builtins) in text editor


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!

dir(builtins) in console

dir(builtins) in text editor


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'>.

type(builtins) in console

type(builtins) in text editor


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'>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement