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

Nick Coghlan ncoghlan at gmail.com
Wed May 26 14:51:42 CEST 2010


On 26/05/10 19:48, Mark Dickinson wrote:
> This is a long way from my area of expertise (I'm commenting here
> because it was me who sent Colin here in the first place), and it's
> not clear to me whether this is a bug, and if it is a bug, how it
> could be resolved.  What would the impact be of having the compiler
> produce 'LOAD_NAME' rather than 'LOAD_GLOBAL' here?

exec with a single argument = module namespace
exec with two arguments = class namespace

Class namespaces are deliberately exempted from lexical scoping so that 
methods can't see class attributes, hence the example in the tracker 
issue works exactly as it would if the code was written as a class body.

   class C:
     y = 3
     def execfunc():
       print y
     execfunc()

With this code, y would end up in C.__dict__ rather than the module 
globals (at least, it would if it wasn't for the exception) and the call 
to execfunc fails with a NameError when attempting to find y.

I know I've closed other bug reports that were based on the same 
misunderstanding, and I didn't understand it myself until Guido 
explained it to me a few years back, so suggestions for improving the 
exec documentation in this area would be appreciated.

Cheers,
Nick.

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


More information about the Python-Dev mailing list