Closures / Blocks in Python

Jeff jeffober at gmail.com
Wed Jul 25 16:45:00 CEST 2007


You can create a lexical closure using a Python generator function,
which allows iteration using a block of code while maintaining
internal state.  A generator is a regular function which uses yield
(like Ruby) to define the point at which the function should return an
expression to the calling code.  For example:

# Generic counter
def counter(min=None, max):
  if not min:
    min = 0
  for i in xrange(min, max):
    yield i
    i = i + 1

When called, this function will yield the value of i and remember its
state.  The next time it's called, it will increment i, then continue
on another iteration of the loop, yielding the new value of i.

For example:

my_counter = counter(0, 10)
my_counter() # <-- 0
my_counter() # <-- 1
for i in my_counter():
  print i
# Prints 2-10 (the remaining numbers in xrange(min, max))




More information about the Python-list mailing list