block scope?

Alex Martelli aleax at mac.com
Sat Apr 7 22:09:50 EDT 2007


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).

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).


Alex



More information about the Python-list mailing list