Python compilers?

Duncan Booth me at privacy.net
Thu May 20 06:44:38 EDT 2004


kveretennicov at yahoo.com (Konstantin Veretennicov) wrote in
news:5155aad2.0405200230.1899e3be at posting.google.com: 

> Carl Banks <imbosol at aerojockey.invalid> wrote in message
> news:<38Yqc.166$eO6.128 at fe2.columbus.rr.com>... 
> 
>> > There's more like it, e.g. the existence of the
>> > locals() dictionary and the ability to modify it.
>> 
>> New feature?  I didn't think modifying the dict returned by locals
>> affected the variables.
>> 
> 
> Evidence of crime :)
> 
> Python 2.3.2
>>>> x
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> NameError: name 'x' is not defined
>>>> locals()['x'] = 1
>>>> x
> 1
> 
> 

That works because you are using locals() to access your global variables. 
Put the same code in a function and it behaves differently:

>>> def test():
...    x = 0
...    locals()['x'] = 1
...    print x
...
>>> test()
0

You cannot depend on the behaviour of modifying locals() remaining 
unchanged over different releases of Python. Bottom line: don't do this.



More information about the Python-list mailing list