block scope?

Georg Brandl g.brandl at gmx.net
Sun Apr 8 14:01:37 EDT 2007


Alex Martelli schrieb:
> Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:
> 
>> aleax at mac.com (Alex Martelli) writes:
>> > > exec?
>> > option 1: that just runs the compiler a bit later ...
>> 
>> Besides exec, there's also locals(), i.e.
>>    locals['x'] = 5
>> can shadow a variable.  Any bad results are probably deserved ;)
> 
>>>> locals['x']=5
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'builtin_function_or_method' object does not support item
> assignment
> 
> I suspect you want to index the results of calling locals(), rather than
> the builtin function itself.  However:
> 
>>>> def f():
> ...   locals()['x'] = 5
> ...   return x
> ... 
>>>> f()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 3, in f
> NameError: global name 'x' is not defined
> 
> No "shadowing", as you see: the compiler knows that x is NOT local,
> because it's not assigned to (the indexing of locals() does not count:
> the compiler's not expected to detect that), so it's going to look it up
> as a global variable (and not find it in this case).

Even assignments to real local variable names in the locals() result do
normally not result in the variable having a new value.

> I think that ideally there should be a runtime error when assigning an
> item of locals() with a key that's not a local variable name (possibly
> excepting functions containing exec, which are kind of screwy anyway).

I would make the locals() result completely independent from the frame,
and document that it is read only.

(though, this needs some other way for trace functions to interact with
the frame's local variables.)

Georg




More information about the Python-list mailing list