Repost: execfile() confusion

Tim Peters tim.one at home.com
Sat Sep 29 04:59:07 CEST 2001


[Nathaniel Gray]
> ...
> Please, somebody, anybody, what's going on??

I'm afraid it takes too long to explain.  The Ref Man warns that mutating
locals won't always work, and you've bumped into a place where it doesn't
work.  So don't do that.  Your life will be much easier if you always pass
an explicit namespace dict (or two, if you care about the local/global
distinction) to execfile.  Uses that don't pass explicit dicts are likely to
get deprecated anyway.

BTW, execfile was originally added for use under the covers by the Emacs
python-mode.  In that context, it was never executed at other than module
scope, where the locals and globals are the same.  Mutating globals (as
opposed to locals) *is* reliable.  If you use execfile without
namespace-dict arguments at other than module scope, I'm afraid the shortest
path to understanding is studying the implementation (in which case you'll
eventually learn-- but without profit --that mutating locals() in fact never
works when calling a function, and that what you're seeing is no deeper than
this:

>>> def f():
...     x = 1
...     locals()['x'] = 42
...     print x
...
>>> f()
1
>>>

).

I could give you tricks to worm around that, but won't without large bundles
of untraceable cash:  seeking to mutate locals by magic is disgusting, and
you can and should find a cleaner (meaning explicit)  approach.

use-the-dict-luke-ly y'rs  - tim





More information about the Python-list mailing list