exec src in {}, {} strangeness

Bernhard Herzog bh at intevation.de
Mon Mar 21 12:57:54 EST 2005


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.


   Bernhard

-- 
Intevation GmbH                                 http://intevation.de/
Skencil                                           http://skencil.org/
Thuban                                  http://thuban.intevation.org/



More information about the Python-list mailing list