Problem with Lexical Scope

Steve Holden steve at holdenweb.com
Mon Dec 12 03:26:59 EST 2005


jslowery at gmail.com wrote:
> I am not completely knowledgable about the status of lexical scoping in
> Python, but it was my understanding that this was added in a long time
> ago around python2.1-python2.2
> 
> I am using python2.4 and the following code throws a "status variable"
> not found in the inner-most function, even when I try to "global" it.
> 
> def collect(fields, reducer):
>     def rule(record):
>         status = True
>         def _(x, y):
>             cstat = reducer(x, y)
>             if status and not cstat:
>                 status = False
>             return y
>         return reduce(_, [record[field] for field in fields])
>     return rule
> 
> What gives?
> 
What's happening is that the interpreter, when it compiles the inner 
function _(), sees an assignment to status and so assumes it is local to 
the _() function. Consequently, since you reference it inside _() before 
assignment you get (I presume) an exception reporting an unbound local 
variable.

The scoping rules do work when you obey them:

  >>> def f1(a, b):
  ...   s = a+b
  ...   def _(x):
  ...     return s+x
  ...   return _
  ...
  >>> func = f1(12, 13)
  >>> func(10)
35
  >>>

Here the nested lexical scopes rule isn't that helpful given the 
overriding nature of assignment within an inner scope. Using global will 
simply put the status variable at *module* scope, which also isn't what 
you want.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list