Paul Rubin <http://[EMAIL PROTECTED]> wrote:

> [EMAIL PROTECTED] (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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to