that matt bone .com |

stupid closure tricks in py3k

This is kind of silly, but I like the nonlocal keyword in Python 3 (well, ok, I like let-bindings in Lisps much much better, but this will do) and how you can get a closure and then poke the insides of the closure to see what it’s up to. I’m sure this isn’t recommended, but it’s a fun trick:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
    def counter():
        a = 0
        def inc():
            nonlocal a
            a+=1
            return a
        return inc
    
    c = counter()
    print(c())
    print(c())
    print(c())
    
    print(c.__closure__[0].cell_contents)

I’d guess the locations of cells in the closure tuple are determined at compile time (i.e. they won’t change between runs), but I haven’t investigated this.