python exec behaves inconsistent with respect to module imports

Peter Otten __peter__ at web.de
Wed Sep 5 12:34:44 EDT 2007


Am Wed, 05 Sep 2007 14:45:11 +0000 schrieb carl.dhalluin at gmail.com:

> So now get back to my exec code in the previous post.
> The exec applies a mixture of both rules
> 1. The exec looks at its namespace to apply the rule for globals().
> Since I'm not at top-level, variables are not auto-populated in the
> globals(), unless I add the keyword 'global' like you suggested.
> 2. However, the exec applies the other rule for locals(). It does NOT
> copy the locals() from one level to the nested one, although it
> should.
> 
> To me this seems a bug in python exec:
> - exec should look at its context to find out if the exec is called
> top-level or deeper
> - if top-level: auto-populate globals, and do not allow inheritance of
> locals to nested levels
> - if non top-level: dont populate globals, but allow inheritance of
> locals to nested levels.

I like your systematic approach.
 
> What do you think?

Too much work :)

Seriously, the local namespace in a normal python function is not a
dictionary, and the decision on how to access a variable is made at
compile time. One way to achieve consistency would be to always use
dictionaries and have the lookup work its way up through the enclosing
namespaces. Of course that would kill performance...

Peter



More information about the Python-list mailing list