22

I am using the built-in module to insert a few instances, so they can be accessed globally for debugging purposes. The problem with the __builtins__ module is that it is a module in a main script and is a dict in modules, but as my script depending on cases can be a main script or a module, I have to do this:

if isinstance(__builtins__, dict):
    __builtins__['g_frame'] = 'xxx'
else:
    setattr(__builtins__, 'g_frame', 'xxx')

Is there a workaround, shorter than this? More importantly, why does __builtins__ behave this way?

Here is a script to see this. Create a module a.py:

#module-a
import b
print 'a-builtin:',type(__builtins__)

Create a module b.py:

#module-b
print 'b-builtin:',type(__builtins__)

Now run python a.py:

$ python a.py 
b-builtin: <type 'dict'>
a-builtin: <type 'module'>
Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
  • For more info, see http://stackoverflow.com/questions/11181519/python-whats-the-difference-between-builtin-and-builtins [Possible Duplicate] – pd12 Aug 11 '15 at 05:24
  • did you try using `import builtins` instead? What results did it give you? I used that as suggested here (https://stackoverflow.com/questions/61084916/how-does-one-make-an-already-opened-file-readable-e-g-sys-stdout/61087617#61087617) and it seems to work. – Charlie Parker Sep 21 '20 at 20:07

1 Answers1

18

I think you want the __builtin__ module (note the singular).

See the docs:

27.3. __builtin__ — Built-in objects

CPython implementation detail: Most modules have the name __builtins__ (note the 's') made available as part of their globals. The value of __builtins__ is normally either this module or the value of this modules’s [sic] __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.

Community
  • 1
  • 1
ars
  • 120,335
  • 23
  • 147
  • 134
  • 2
    What about Python3? `NameError: name '__builtin__' is not defined` – warvariuc Mar 03 '14 at 06:28
  • 5
    @warvariuc: the module was renamed to [`builtins`](https://docs.python.org/3/library/builtins.html). – Martijn Pieters Jan 20 '15 at 16:35
  • can you answer the title of the question? is `__builtins__` a dict or not? and when is it one or the other? The small details of the OP aren't as relevant as the searchable title given by search engines. Please answer that. – Charlie Parker Sep 21 '20 at 19:35