problem with execfile

Stephan Houben stephan at pcrm.win.tue.nl
Tue Aug 31 11:25:40 EDT 1999


Berthold Hoellmann <hoel at GermanLloyd.org> writes:

> Hello,
> 
> I have a problem with execfile:
> 
> python
> Python 1.5.2 (#2, Jul  7 1999, 09:18:40) [C] on sunos5
> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
> >>> def x():
> ...     execfile("ZustandsDaten.dat")
> ...     print dir()
> ...     print Tiefgang
> ... 
> >>> x()
> ['Pitch', 'Tiefgang', 'U', '__doc__', 'array', 'n']
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 4, in x
> NameError: Tiefgang
> >>> 
> 
> Why is Tiefgang unknown in the function x?

This one is very subtle. Here's my take on it.
(But I'm not Tim, so I might be wrong.)

The problem is in a compile-time optimization made by
Python. Any local variables (like Tiefgang) are put
in a special array that's much faster than the ordinary
locals() dictionary. But execfile() uses the ordinary locals()
dictionary. So when "print Tiefgang" happens, Python tries
to look it up in the special array. But it's not there,
so a NameError is generated.

Is this a bug or a feature? I don't know. But I do know
how to kludge around it: just add a phony "exec" statement,
something like `exec "1"'. This will prevent the compiler
from doing this optimization, and then your code will work.

Greetings,

Stephan







More information about the Python-list mailing list