[Python-Dev] variable name resolution in exec is incorrect (original) (raw)

Guido van Rossum guido at python.org
Thu May 27 02:44:21 CEST 2010


On Wed, May 26, 2010 at 5:37 PM, Colin H <hawkett at gmail.com> wrote:

Mark Dickinson wrote:

Seems to me the whole idea of being able to specify separate global and local scopes for top-level code is screwy in the first place. Are there any use cases for it? Maybe the second scope argument to exec() should be deprecated? It is running as class namespace that makes the argument that there's no use case. I agree - I can't think of any decent use cases for exec() as class namespace - defining functions and classes only works for a subset of function and class definitions However, if exec() ran as function namespace instead, then the locals dictionary will contain all the definitions from the exec()'d code block, and only those definitions. Very useful.

Hmm... I see your point, but fear that the implementation is tricky, since it would mean every exec'ed block would have to be compiled as if it were a function body, and that probably violates some other invariants.

This is a major use case for exec() - defining code from strings (e.g. enabling you to store python code in the database), and using it at runtime. It seems to me this must have been the point of locals in the first place.

If you just use globals, then your definitions exist amongst a whole bunch of other python stuff, and unless you know in advance what was defined in your code block, its very difficult to extract them.

Check the reconstruction of your use case I just posted. I think you re thinking context == globals(), which makes sense.

-- --Guido van Rossum (python.org/~guido)



More information about the Python-Dev mailing list