[Python-Dev] Explicit Lexical Scoping (pre-PEP?)

Nick Coghlan ncoghlan at gmail.com
Fri Jul 7 12:29:21 CEST 2006

skip at pobox.com wrote:
>     jan-python> So.. are we only thinking about implementing this outer
>     jan-python> scope assignment because there's lots of talk about it on
>     jan-python> the list, ...
> :-)
>     jan-python> ... or are there actually use cases that would become
>     jan-python> clearer if assigning to an outer scope variable was allowed?
> I think full lexical scoping will only be of use to people who use nested
> scopes heavily.  The more typical user will be happy to just refer to values
> in outser scopes without modifying them and rely on classes to save changed
> state across calls.  I think it's almost a YAGNI, but I'm sure others will
> disagree.

I think it falls into the same category as Guido's ultimate acceptance of PEP 
308. There are assorted ways to live *without* conditional expressions, but 
each of the workarounds for its absence had issues. Switching to a statement 
worked properly, but meant you didn't have a single expression any more. Use 
the and-or trick kept the single expression characteristic, but was easy to 
get wrong. Hence, PEP 308: One Obvious Way to do it, assuming you want to do 
it in the first place.

I think writing to outer scopes is similar. You can box the variable, or make 
it an attribute of an object, but either approach requires you to refactor 
*all* uses of the variable, rather than just the one you currently care about. 
Hence, 'nonlocal': One Obvious Way to do it, assuming you want to do it in the 
first place.

That way, when you're *reading* the code of someone who likes to use such 
tricks, you only need to know how to read the one obvious way, rather than 
having to decipher whichever method they've chosen to work around the limitation.

The perennial accumulator example still takes 6 lines, though:

def accumulator(n):
     def increment(i):
         nonlocal n
         n += i
         return n
     return increment


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list