Modifying func_closure

Robert Brewer fumanchu at amor.org
Fri Jul 9 17:13:48 EDT 2004


Jacek Generowicz wrote:
> I think that I am trying to modify g.func_closure[0]
> 
> I'm trying to do something like the following. (I'm no Schemer, so
> there may well be a more concise way of putting it.)
> 
>   (define closures
>     (let ((enclosed 1))
>       (define (report) enclosed)
>       (define (modify new) (set! enclosed new))
>       (list report modify)))
>   
>   (define report (car closures))
>   (define modify (cadr closures))
>   
>   (report)    ; -> 1
>   (modify 2)
>   (report)    ; -> 2

I'm no Schemer either, but I'm going to take a shot at the equivalent
pseudo-Python:

def closures():
    enclosed = [1]
    def report():
        return enclosed[0]
    def modify(new):
        enclosed[0] = new
        return enclosed[0]
    return report, modify

report, modify = closures()
report()
modify(2)
report()

...so there are ways to fake it using mutation rather than rebinding.

Which immediately brings up the question: why not use a class instead?

class Closure(object):
    def __init__(self):
        self.enclosed = 1
    
    def report(self):
        return self.enclosed
    
    def modify(self, new):
        self.enclosed = new

...but I assume you have your reasons. ;)


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list