Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why __builtins__ is both module and dict

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'>
like image 568
Anurag Uniyal Avatar asked Jul 26 '09 08:07

Anurag Uniyal


1 Answers

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.

like image 124
ars Avatar answered Sep 22 '22 09:09

ars