[Python-Dev] Re: closure semantics

David Eppstein eppstein at ics.uci.edu
Sat Oct 25 14:05:38 EDT 2003


In article <200310251640.h9PGePZ07536 at 12-236-54-216.client.attbi.com>,
 Guido van Rossum <guido at python.org> wrote:

> > > or at run-time) always goes from inner scope to outer.  While you and
> > > I see nested functions as small amounts of closely-knit code, some
> > > people will go overboard and write functions of hundred lines long
> > > containing dozens of inner functions, which may be categorized into
> > 
> > This doesn't look like a legitimate use case to me; i.e., I see no need
> > to distort the language if the benefit goes to such "way overboard" uses.
> > I think they will have serious maintainability problems anyway.
> 
> One person here brought up (maybe David Eppstein) that they used this
> approach for coding up extensive algorithms that are functional in
> nature but have a lot of state referenced *during* the computation.
> Whoever it was didn't like using classes because the internal state
> would persist past the lifetime of the calculation.

Yes, that was me.  You recommended refactoring the stateful part of the 
algorithm as an object despite its lack of persistence.  It worked and 
my code is much improved thereby.

Specifically, I recognized that one of the outer level functions of my 
code was appending to a sequence of strings, so I turned that function 
into the next() method of an iterator object, and the other nested 
functions became other methods of the same object.

I'm not sure how much of the improvement was due to using an 
object-oriented architecture and how much was due to the effort of 
refactoring in general, but you convinced me that using an object to 
represent shared state explicitly rather than doing it implicitly by 
nested function scoping can be a good idea.

-- 
David Eppstein                      http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science




More information about the Python-Dev mailing list