Closures in python

Syver Enstad syver at inout.no
Thu Sep 18 13:32:43 CEST 2003


kbilsted at it-c.dk (Kasper B. Graversen) writes:

> Having played with Smalltalk for the past month, I'm getting used to
> passing code as arguments to methods... how easy is it to do this in
> python? I haven't seen any recent postings on this subject here...

It is fairly straightforward:

import sys

def funcThatTakesCallable(aCallable):
    aCallable('SomeString')

class MyClass:
    def myFunc():
        def myCallable(arg):
            print arg
        funcThatTakesCallable(myCallable)
        funcThatTakesCallable(self.anotherCallable)
        funcThatTakesCallable(lambda arg: sys.stdout.write('%s\n' % arg))

    def anotherCallable(self, arg):
        print 'another', arg


The major difference is that the anonymous form of a function (lambda)
isn't allowed to contain statements, only an expression. This is
rather crippling for Smalltalk/Ruby style coding and seems to lead to
warts like list comprehensions instead of having simple methods in the
collection interface that takes a block/lambda and calls this for each
element of the collection.

Example:

newCollection = [each for each in collection if each != 'Sausage']

newCollection = collection.select(lambda each: each != 'Sausage')






More information about the Python-list mailing list