""" Examples demonstrating that Python has Lisp-like closures (counter()) and that there's a bit of trickyness (counter2()) >>> from counters import * >>> c1 = counter() >>> c2 = counter() >>> c1() 1 >>> c1() 2 >>> c2() 1 >>> cc1 = counter2() >>> cc1() Traceback (most recent call last): File "", line 1, in ? File "counters.py", line 12, in _inc x += step UnboundLocalError: local variable 'x' referenced before assignment >>> """ def counter(start=0, step=1): """Defines and returns a new function that will act as a counter with initial value start and increment step. Each time that functions is called it will increment the counter by step and return the new value. """ x = [start] def _inc(): x[0] += step return x[0] return _inc def counter2(start=0, step=1): """This one does not work""" x = start def _inc(): x += step return x return _inc