problem with execfile

Tim Peters tim_one at email.msn.com
Wed Sep 1 01:56:18 EDT 1999


[Berthold Hoellmann]
> I have a problem with execfile:

I'd stick to using this at top level -- in the dim mists of history, execfile
was introduced to help the Emacs python-mode (& similar tools) send chunks of
top-level code to a Python process.

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

Well, as far as Python knows, execfile isn't anything special -- it's just
another function.  By the usual rules, then, Tiefgang is considered to be a
global name (there's no binding of Tiefgang in x).  So while your dir() shows
that Tiefgang did get bound in the locals, the print isn't going to look in the
locals to find it -- it skips the locals and goes straight to the module
globals.  Where Tiefgang isn't.

As Stephen said, you can fool it into doing what you want by inserting a (any)
"exec" statement.  Unlike execfile, exec *is* special (it's a statement, not a
function), and when Python sees an "exec" in a function it generates much
slower code that gives up trying to figure out which names are local and which
global, always looking up every name starting with the locals.

A more straightforward way to get what you want is to replace the execfile with

    exec open("ZustandsDaten.dat").read()

there's-only-one-way-to-do-it-ly y'rs  - tim






More information about the Python-list mailing list