Hacker News new | ask | show | jobs
by andolanra 5649 days ago
Python actually does have proper lexical scope and real closures (as of version 2.2, I think), so you can do

    def set_adder():
        s = set()
        def add(item):
            s.add(item)
            return s
        return add
and it'll work the same way. The problem really comes in the fact that before Python 3, all assignment took place in the local scope, so anything involving assignment (such as the counter example) doesn't work. You can sidestep it in Python 2.6 using the same kind of trick:

    def make_counter():
        value = [0]
        def count():
            temp, = value
            value[0] += 1
            return temp
        return count
which is sort of hacky but works. (Other languages sidestep this by having some other way of specifying declaration-versus-assignment, such as JavaScript's var keyword for variable declaration.)