Re: Problem with Lexical Scope
- From: Steve Holden <steve@xxxxxxxxxxxxx>
- Date: Mon, 12 Dec 2005 08:26:59 +0000
jslowery@xxxxxxxxx wrote:
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.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?
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/
.
- Follow-Ups:
- Re: Problem with Lexical Scope
- From: Bengt Richter
- Re: Problem with Lexical Scope
- From: jslowery@xxxxxxxxx
- Re: Problem with Lexical Scope
- References:
- Problem with Lexical Scope
- From: jslowery@xxxxxxxxx
- Problem with Lexical Scope
- Prev by Date: Re: lambda (and reduce) are valuable
- Next by Date: Re: slice notation as values?
- Previous by thread: Re: Problem with Lexical Scope
- Next by thread: Re: Problem with Lexical Scope
- Index(es):
Relevant Pages
|