What are python closures realy like?

Paul Boddie paul at boddie.org.uk
Wed Dec 6 07:04:36 EST 2006


Fredrik Lundh wrote:
>
> when doing some heavy optimization, I recently found myself writing:
>
>     def foobar(arg1, arg2, arg3):
>         def helper(arg):
>              do something with arg1 and argument
>         def foo():
>              do something with arg1 and arg3 and
>              call helper
>         def bar():
>              do something with arg1 and arg2
>         def zoo():
>              do something with arg2 and arg3 and
>              call helper
>        # oops; how do I return all these?
>         class bag(object):
>              pass
>         bag = bag()
>         bag.foo = foo
>         bag.bar = bar
>         bag.zoo = zoo
>         return bag
>
> which, I think, deserves no further comment...

Have I missed something deep here, or could you not have written the
above as follows...?

class foobar(object):
    def __init__(self, arg1, arg2, arg3):
        self.arg1, self.arg2, self.arg3 = arg1, arg2, arg3
    def helper(self, arg):
        do something with arg1 and argument
    def foo(self):
        do something with arg1 and arg3 and
        call helper
    def bar(self):
        do something with arg1 and arg2
    def zoo(self):
        do something with arg2 and arg3 and
        call helper

There's certainly some boilerplate required (in both forms, though) and
you'd have to use self in various places, but the above looks less
contorted to me. I'd like to hear your further comment, however, since
the principal inconvenience of making a class seems to be in the
verbose initialisation and explicit self, the latter of which obviously
being a feature that you won't find me complaining about, though. ;-)

Paul




More information about the Python-list mailing list