lexical closures and python

Ignacio Vazquez-Abrams ignacio at openservices.net
Thu Sep 6 11:03:06 CEST 2001

On Thu, 6 Sep 2001, John Beppu wrote:

> Notice how grande and pequeno remember the value of current, but
> also notice that they each remember their own current variable.
> Because current is lexically bound to a new closure each time
> sequence_iterator() is invoked, grande and pequeno do not
> interfere with each other.
> Interesting, no?

Yes. The Pythonic equivalent (as I know it) would be:

class sequence_iterator:
  def __init__(self, a):
  def __call__(self):
    b, self.a=self.a, self.a+1
    return b


for i in range(5):
  print grande()
  print pequeno()

Ignacio Vazquez-Abrams  <ignacio at openservices.net>

More information about the Python-list mailing list