execfile() and locals()

Thomas Jollans thomas at jollybox.de
Sun Aug 15 23:55:06 CEST 2010


On Sunday 15 August 2010, it occurred to fons at kokkinizita.net to exclaim:
> Hello all,
> 
> The documentation on execfile() and locals() makes it clear that code
> executed from execfile() can not modify local variables in the function
> from wich execfile() was called. Two questions about this:
> 
> 1. Is there some way to circumvent this limitation (apart from explicitly
> copying variables to/from a dictionary passed as locals to execfile()) ?
> 
> 2. (for experts only I guess) I'd like to understand *why* this is the
> case.

You can't assign to local variables via  locals(), or in any way at all, 
except by assigning locally.

>>> def f():
...     x = 1
...     locals()['x'] = 2
...     return x
... 
>>> f()
1
>>> 

The reason is, I think, that local variable access is optimized: variables you 
assign inside the function are defined to be local (unless you specify 
otherwise), and a fetching a local variable doesn't involve an expensive may-
or-may-not-work dict lookup:

>>> x = 1
>>> def g():
...     x
...     x = 2
... 
>>> x
1
>>> g()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in g
UnboundLocalError: local variable 'x' referenced before assignment
>>> 

If a local variable assignment were hidden behind an execfile(), or a
"from foo import *", or a locals()[...] assignment, it wouldn't be possibly to 
tell if something is local or not.



More information about the Python-list mailing list