exec(), execfile() and local-variable binding?

Steven Taschuk staschuk at telusplanet.net
Sun Aug 10 02:50:35 EDT 2003


Quoth Jonathan:
  [...]
> Well, that's understandable. But what I find strange is that exec()
> *doesn't* work in this way. Consider this version:
> 
> # main_exec.py
> def f() :
>         exec("x = 1")
>         print "x:", x

Note that exec is a keyword, not a function; you might as well
write
    exec 'x = 1'
I'm not just picking a nit here -- it is important for your
question that exec is a keyword, since this means it is possible
to determine at compile-time whether exec is used in the body of a
function.  This is quite unlike calls to built-in functions such
as execfile(), which cannot in general be identified as such at
compile-time.

As you noted, in the presence of exec statements, the compiler
abandons the optimization by which LOAD_NAMEs are replaced with
LOAD_GLOBALs.  This optimization normally speeds up variable
access by skipping a futile name lookup in the locals; abandoning
this optimization when there are exec statements makes your
example above work in the obvious and desired way.

-- 
Steven Taschuk                staschuk at telusplanet.net
"I tried to be pleasant and accommodating, but my head
 began to hurt from his banality."   -- _Seven_ (1996)





More information about the Python-list mailing list