From: Steven D'Aprano on
On Tue, 15 Jun 2010 15:22:17 -0700, Peter wrote:

> I checked help on execfile and could only find the following
> (mystifying) sentence:
>
> "execfile() cannot be used reliably to modify a function's locals."

What is mystifying about it? It's short and clear -- execfile cannot be
used to reliably modify a function's local variables.

The *reason* why this is so is complicated, but the fact that it is so is
plain and simple, as you already discovered.



--
Steven
From: Steven D'Aprano on
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