Execfile() - bug / strange behavior

Tim Peters tim_one at email.msn.com
Fri Feb 4 08:36:24 CET 2000


{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()
>
>
> Then I have 1.txt:
> a = 5
> b = 8
>
> When I run this, I expect to see a is 5, but I get:
>
> 3
> {'b': 8, 'a': 3}
>
> I don't understand why variable a is not set, but b is!  Even
> stranger, when I try to print b from timbot(), it gives me NameError,
> even though it's in locals()!
>
> When I change execfile("1.txt") to exec open("1.txt",'r').read(), it
> works just fine!
> ...

This may (or may not) be related to a long-standing bug recently fixed; try
the latest CVS version of Python.  The reason I suspect this is that

    exec compile(open("1.txt").read(), "", "exec")  # line 666

works exactly the same way (in this case) as your execfile version (and not
the same way as your exec version), and this one is due to a legit bug in
the way "exec" deals with compiled code objects (as opposed to strings).
And line 666 is *almost* faking "by hand" what execfile does by magic.
OTOH, Gordon is also right that while the presence of the exec *stmt* causes
Python to disable local-vrbl optimizations, the presence of the mere builtin
"execfile" function does not.

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.

if-you-play-with-fire-expect-a-good-time<wink>-ly y'rs  - tim






More information about the Python-list mailing list