setting variables in outer functions

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Nov 4 08:49:57 EST 2007


Hrvoje Niksic a écrit :
> "Chris Mellon" <arkanes at gmail.com> writes:
> 
> 
>>I have no idea why someone who already has a working, object system
>>would want to implement their own on top of closures.
> 
> 
> This subthread is getting ridiculous -- closures are *not* useful only
> for implementing object systems!  The object system thing is just a
> method of teaching abstractions popularized by SICP.  Abstractions
> normally taken for granted, such as objects, or even expression
> evaluation, are implemented from scratch, using only the most basic
> primitives available.  In a Lisp-like language with lexical scope, the
> most basic storage primitive is the lexical environment itself[1].
> 
> In real-life code, closures are used to implement callbacks with
> automatic access to their lexical environment without the need for the
> bogus additional "void *" argument one so often sees in C callbacks,
> and without communication through global variables.  If the callbacks
> can access variables in the outer scope, it's only logical (and
> useful) for them to be able to change them.  Prohibiting modification
> reduces the usefulness of closures and causes ugly workarounds such as
> the avar[0] pattern.
> 
> If closures were useful only for implementing bogus object systems,
> neither they nor "nonlocal" would have made it to Python in the first
> place.
> 

Indeed. But please read carefully the classic piece of wisdom quoted by 
Diez in his answer. Then remember that in Python, callable objects 
doesn't need to be functions, and most of what can be done (and is 
usually done in FPLs) can be done with objects. Look at the sample 
Python implementation of partial evaluation, or at all the so-called 
decorators that are not functions but really classes.

I do use Python's closures quite a lot myself, because it's often 
simpler than doing it the OO way. But for whatever slightly more 
involved, I prefer to write my own classes, and I'll still do so if and 
when Python grows "full-blown" closures.



More information about the Python-list mailing list