Execfile() - bug / strange behavior

Gordon McMillan gmcm at hypernet.com
Fri Feb 4 21:27:55 EST 2000


Carel Fellinger wrote:

> Tim Peters <tim_one at email.msn.com> wrote:
> > {Amit Patel]
> >> I'm trying to understand why execfile(fn) is different from exec
> >> open(fn,'r').read().  Here's my program:
> >>
> >> def timbot():
> >>     a = 3
> >>     execfile("1.txt")
> >>     print a
> >>     print locals()
> >> timbot()
> >>
> >>
> 
> > You can't actually get the timbot interested in pursuing this, since it
> > never uses these things without explicity naming the dicts it wants used as
> > execution context.
> 
> And how then would it pass on the locals dict in this case? According to
> the docs, and a recent explanation on this list, it is not possible to
> use something like execfile("1.txt", globals(), locals()), as those are
> readonly in case of functions! One of the few dark corners of Python IMHO.

In this case:

>>> d = {'a':3}
>>> execfile('1.txt', {}, d)
>>> d
{'b': 8, 'a': 5}
>>>

The only reason for using execfile is if you don't know what the 
file contains. Thus you wouldn't know what names it will 
introduce. So the only sane way of dealing with it is with an 
explicit dict. KeyErrors are easier to deal with than 
NameErrors.

- Gordon




More information about the Python-list mailing list