exec("dir()",d)

  • Thread starter Emanuele D'Arrigo
  • Start date
E

Emanuele D'Arrigo

Greetings everybody,

I don't quite understand why if I do this:

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?

Manu
 
M

Mel

Emanuele said:
Greetings everybody,

I don't quite understand why if I do this:


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.{'__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'>,

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


Mel.
 
E

Emanuele D'Arrigo

Thank you both for the explanation.

As a matter of fact RTFM doesn't -always- help. Sometimes I'm just
thick and I can read the manual 10 times and still not understand, as
it happened on this particular matter. Your contribution focused my
attention on the right bit of the manual which I somehow didn't manage
to ingest before. Now I understand.

Thank you.

Manu
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,201
Messages
2,571,048
Members
47,647
Latest member
NelleMacy9

Latest Threads

Top