Repost: execfile() confusion

Nathaniel Gray n8gray at caltech.edu.is.my.e-mail.address.com
Sun Sep 30 04:06:06 EDT 2001


Tim Peters wrote:
> [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.

Ah.  "Here there be dragons."  I suspected that might be the answer.  Where in 
the Ref Man does it talk about mutating locals?  Aha, in the description of 
locals(), sensibly enough.

> [snip] 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
>>>>

Most enlightening!

> 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.

Yeah, yeah, I know.  I just like to be evil every now and then.  It's just 
plain fun.  You should see my object-oriented Matlab code.  ;-)

-n8

-- 
Nathaniel Gray

California Institute of Technology
Computation and Neural Systems
--




More information about the Python-list mailing list