problem with exec and locals()
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Fri Jul 11 05:41:32 EDT 2008
En Fri, 11 Jul 2008 03:51:39 -0300, Uwe Schmitt
<rocksportrocker at googlemail.com> escribi�:
> On 1 Jul., 15:15, Mel <mwil... at the-wire.com> wrote:
>> rocksportrockerwrote:
>>
>> > the following code does not work until I ommit the "a=0" statement.
>>
>> > def test():
>> > exec "a=3" in locals()
>> > print a
>> > a=0
>>
>> > test()
>>
>> > print raises:
>> > UnboundLocalError: local variable 'a' referenced before
>> > assignment
>>
>> > Can anybody explain what is going wrong here ?
>>
>> AFAIK, local variables are implemented rather like __slots__ in
>> new-style
>> classes. This is a very valuable efficiency measure, but it can cause
>> this
>> kind of trouble. Without `a=0`, the bytecode compiler makes no slot
>> for a,
>
> Thanks for your answer. I wonder if this is a bug, or did I miss
> something
> in the docs ???
Read the warnings in the docs for the locals() builtin function:
http://docs.python.org/lib/built-in-funcs.html#l2h-47
and the execfile function:
http://docs.python.org/lib/built-in-funcs.html#l2h-26
--
Gabriel Genellina
More information about the Python-list
mailing list