exec("dir()",d)

Mel mwilson at the-wire.com
Sun Aug 9 14:50:41 CEST 2009


Emanuele D'Arrigo wrote:

> Greetings everybody,
> 
> I don't quite understand why if I do this:
> 
>>>> d = {}
>>>> exec("dir()", d)
> 
> 1) d is no longer empty
> 2) the content of d now looks like __builtins__.__dict__ but isn't
> quite it d == __builtins__.__dict__ returns false.
> 
> Can anybody shed some light?

You should check up on what exec does.  In this case it runs a string 
containing code using dictionary `d` as its global namespace, and so `d` has 
to contain the usual global namespace symbols -- otherwise `dict` can't 
work.  `__builtins__.__dict__ is one of the elements in the global 
namespace, not the namespace itself.  Another example:


Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a=7
>>> d={'b':a}
>>> exec ("print b", d)
7
>>> d
{'__builtins__': {'bytearray': <type 'bytearray'>, 'IndexError': <type 
'exceptions.IndexError'>, 'all': <built-in function all>, 'help': Type 
help() for interactive help, or help(object) for help about object., 'vars': 
<built-in function vars>, 'SyntaxError': <type 'exceptions.SyntaxError'>, 
'unicode': <type 'unicode'>, 'UnicodeDecodeError': <type 
'exceptions.UnicodeDecodeError'>, 'isinstance': <built-in function 
isinstance>, 'copyright': Copyright (c) 2001-2009 Python Software 
Foundation.
[ ... ]
'AssertionError': <type 'exceptions.AssertionError'>, 'classmethod': <type 
'classmethod'>, 'UnboundLocalError': <type 'exceptions.UnboundLocalError'>, 
'NotImplementedError': <type 'exceptions.NotImplementedError'>, 
'AttributeError': <type 'exceptions.AttributeError'>, 'OverflowError': <type 
'exceptions.OverflowError'>}, 'b': 7}
>>> 

To get rid of the name error, you'd need
d={}
d['d'] = d
exec ("dir (d)", d)


	Mel.




More information about the Python-list mailing list