exec throws an exception...why?

Hung Jung Lu hungjunglu at yahoo.com
Mon Jun 7 15:09:08 EDT 2004


nicksjacobson at yahoo.com (Nick Jacobson) wrote:
> 
> "If the [local variable] definition occurs in a function block, the
> scope extends to any blocks contained within the defining one..."

Strictly speaking, the above statement still holds true. That is, from
a lawyer's point of view. :)

> But, the following code fails, saying that y is undefined:
> 
> def main():
> 	s = \
> """
> y = 3
> def execfunc():
> 	print y
> execfunc()
> """
> 	d = {}
> 	e = {}
> 	exec s in d, e
> 
> if __name__ == '__main__':
> 	main()

Very good example.

> Conclusion:
> 
> Is code from the exec statement on the module level or not?  It
> doesn't get its locals mapped to globals.  But it also doesn't get its
> local variables nested.  So it gets neither benefit.  IMO it should
> get one or the other.  i.e. the second piece of code should work.

The exec statement is usually considered an slightly advanced topic.
And frankly I think people that use it at the module level would be
minority. So, having its behavior parallel to the case of nested-scope
would seem to make more sense, to me. Remember also that the "global"
statement can be used inside the code string, which is reminiscence
that we are inside a local scope, just like the case of function. So,
if you wish, the inconsistency could be considered as a bug in Python,
and it may even be good idea to submit a bug report. After all, nested
scope is considered a relative new feature, given Python's history
(over a decade.)

Or there may be some obscure way of tweaking things so to convince
Python that it is inside a function scope at the moment of "def
execfunc():"... Anyway, we are talking about voodoo magic here... :)

regards,

Hung Jung



More information about the Python-list mailing list