
here's a simple (but somewhat strange) test program: def spam(): a = 1 if (0): global a print "global a" a = 2 def egg(): b = 1 if 0: global b print "global b" b = 2 egg() spam() print a print b if I run this under 1.5.2, I get: 2 Traceback (innermost last): File "<stdin>", line 19, in ? NameError: b </F>

I would take a guess that the "if 0:" is optimized away *before* the inspection for a "global" statement. But the compiler doesn't know how to optimize away "if (0):", so the global statement remains. Ah. Just checked. Look at compile.c::com_if_stmt(). There is a call to "is_constant_false()" in there. Heh. Looks like is_constant_false() could be made a bit smarter. But the point is valid: you can make is_constant_false() as smart as you want, and you'll still end up with "funny" global behavior. Cheers, -g On Thu, Dec 14, 2000 at 02:19:08PM +0100, Fredrik Lundh wrote:
-- Greg Stein, http://www.lyra.org/

Note that the behavior of both functions is undefined ("Names listed in a global statement must not be used in the same code block textually preceding that global statement", from the Lang Ref, and "if" does not introduce a new code block in Python's terminology). But you'll get the same outcome via these trivial variants, which sidestep that problem: def spam(): if (0): global a print "global a" a = 2 def egg(): if 0: global b print "global b" b = 2 *Now* you can complain <wink>.

I would take a guess that the "if 0:" is optimized away *before* the inspection for a "global" statement. But the compiler doesn't know how to optimize away "if (0):", so the global statement remains. Ah. Just checked. Look at compile.c::com_if_stmt(). There is a call to "is_constant_false()" in there. Heh. Looks like is_constant_false() could be made a bit smarter. But the point is valid: you can make is_constant_false() as smart as you want, and you'll still end up with "funny" global behavior. Cheers, -g On Thu, Dec 14, 2000 at 02:19:08PM +0100, Fredrik Lundh wrote:
-- Greg Stein, http://www.lyra.org/

Note that the behavior of both functions is undefined ("Names listed in a global statement must not be used in the same code block textually preceding that global statement", from the Lang Ref, and "if" does not introduce a new code block in Python's terminology). But you'll get the same outcome via these trivial variants, which sidestep that problem: def spam(): if (0): global a print "global a" a = 2 def egg(): if 0: global b print "global b" b = 2 *Now* you can complain <wink>.
participants (3)
-
Fredrik Lundh
-
Greg Stein
-
Tim Peters