exec src in {}, {} strangeness

Stefan Seefeld seefeld at sympatico.ca
Mon Mar 21 13:03:07 EST 2005


Bernhard Herzog wrote:
> Stefan Seefeld <seefeld at sympatico.ca> writes:
> 
> 
>>Is there anything wrong with 'exec source in a, b' where
>>a and b are distinc originally empty dictionaries ? Again,
>>my test code was
>>
>>class Foo: pass
>>class Bar:
>>   foo = Foo
>>
>>and it appears as if 'Foo' was added to 'a', but when evaluating
>>'foo = Foo' the interpreter only looked in 'b', not 'a'.
> 
> 
> No, it's the other way round.  Foo is added in b since bindings are done
> in the local scope.  Your case is a bit more complicated, though.
> Here's what I think happens:
> 
> class Foo is bound in b, the locals dictionary, so there is no reference
> to Foo in the globals dictionary.  The body of class B is executed with
> it's own new locals dictionary.  That locals dictionary will effectively
> be turned into Bar.__dict__ when the class object is created.
> 
> When "foo = Foo" is executed, Foo is first looked up in that new locals
> dictionary.  That fails, so it's also looked up in the globals
> dictionary a.  That fails as well because Foo was bound in b.  The final
> lookup in the builtins also fails, and thus you get an exception.

Thanks for the explanation ! I'm still unable to make a conclusion:
What is wrong ? Am I doing something stupid (I did try various things
such as inserting __builtin__ into the dictionary, etc.) ?
Or is that really a bug ?

Thanks,
		Stefan



More information about the Python-list mailing list