Modifying func_closure

Robert Brewer fumanchu at
Fri Jul 9 23:13:48 CEST 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

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() 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
Amor Ministries
fumanchu at

More information about the Python-list mailing list