views:

117

answers:

1

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

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

so is there a workaround, shorter than this, and more importantly I wanted to know why __builtins__ behaves this way?

here is script to see this, create a module a.py

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

create 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'>
+4  A: 

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

See the docs:

28.2. __builtin__ — Built-in objects

As an 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 __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.

ars