[Python-Dev] variable name resolution in exec is incorrect

Nick Coghlan ncoghlan at gmail.com
Thu May 27 02:12:30 CEST 2010


On 27/05/10 06:07, Colin H wrote:
>> In original Python, the snippet would have given an error whether you
>> thought of it as being in a class or function context, which is how
>> anyone who knew Python then would have expected. Consistency is not a bug.
>
>> When nested function namespaces were introduced, the behavior of exec
>> was left unchanged. Backward compatibility is not a bug.
>
> Generally, most other behaviour did change - locals in enclosing
> scopes *did* become available in the nested function namespace, which
> was not backward compatible.  Why is a special case made to retain
> consistency and backward compatibility for code run using exec()? It's
> all python code. Inconsistent backward compatibility might be
> considered a bug.

Because strings are opaque to the compiler. The lexical scoping has *no 
idea* what is inside the string, and the exec operation only has 3 
things available to it:
  - the code object compiled from the string
  - the supplied globals namespace
  - the supplied locals namespace

It isn't a special case, it's the only way it can possible work.

Consider a more complex example:

   def get_exec_str():
     y = 3
     return "print(y)"

   exec(get_exec_str())

Should that code work?

Or consider this one:

   def get_exec_str():
     y = 3
     return "print y"

   def run_exec_str(str_to_run):
     y = 5
     exec(str_to_run)

   run_exec_str(get_exec_str())

Should that work? If yes, should it print 3 or 5?

Lexical scoping only works for code that is compiled as part of a single 
operation - the separation between the compilation of the individual 
string and the code defining that string means that the symbol table 
analysis needed for lexical scoping can't cross the boundary.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------


More information about the Python-Dev mailing list