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

Nick Coghlan ncoghlan at gmail.com
Wed May 26 15:43:35 CEST 2010


On 26/05/10 23:08, Michael Foord wrote:
> On 26/05/2010 13:51, Nick Coghlan wrote:
>> 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.
>
> Your explanation here is very clear. Is this in the documentation?

It isn't actually - I think Thomas may be right that the current exec 
documentation was largely written prior to the introduction of lexical 
scoping. So adding something along these lines would probably be a good 
place to start.

Unfortunately, even my explanation above isn't 100% correct - it misses 
a subtle distinction where lexical scoping will pass through a class 
definition nested inside a function definition and see the function 
scope, but the use of strings for exec code means that the scopes of any 
containing functions are ignored completely.

Cheers,
Nick.

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


More information about the Python-Dev mailing list