Scope (?) question

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Jun 16 08:30:49 EDT 2010


On Tue, 15 Jun 2010 17:12:47 -0700, Inyeol Lee wrote:

> > "execfile() cannot be used reliably to modify a function’s locals."
[...]
> This is due to CPython's static optimization of local name lookup. Dummy
> 'exec' statement disables this and makes your example work:
> 
> def X():
>   exec "None"
>   execfile('test-data.py')
>   print data


Is this documented anywhere? It looks like a nasty hack that is liable to 
disappear at any time. In fact, it looks like a nasty hack which *has* 
disappeared: it doesn't work in Python 3.1:


>>> open('test.py').read()
'x = 2'
>>> def f():
...     exec("None")
        # execfile doesn't exist any longer
...     exec(open('test.py').read())
...     print(x)
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in f
NameError: global name 'x' is not defined


By experimentation in Python 2.5, it seems to me that it only works if 
the local variable hasn't already been defined. If it has, you can't 
modify it:

>>> def f():
...     x = 1
...     exec("None")
...     execfile('test.py')
...     print x
...
>>> f()
1


But you can use it to define new locals:

>>> def f():
...     exec("None")
...     execfile('test.py')
...     print x
...
>>> f()
2




-- 
Steven



More information about the Python-list mailing list