Execfile() - bug / strange behavior
Gordon McMillan
gmcm at hypernet.com
Thu Feb 3 22:24:06 EST 2000
Amit Patel writes:
> 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()!
Perhaps this will give you a hint:
>>> execfile('1.txt')
>>> a
5
>>> b
8
>>>
> When I change execfile("1.txt") to exec open("1.txt",'r').read(), it
> works just fine!
That's because in the presence of an "exec" statement, locals
don't get optimized to slots. As a function "execfile" gets no
such special treatment. If you really want to use execfile,
pass in the optional dicts and suck the values out of there.
not-a-bot-ly y'rs
- Gordon
More information about the Python-list
mailing list