lexical closures and python

Heiko Wundram heikowu at ceosg.de
Thu Sep 6 07:08:08 EDT 2001


On Thursday 06 September 2001 11:03, you wrote:
>
> Yes. The Pythonic equivalent (as I know it) would be:
>
> class sequence_iterator:
>   a=None
>   def __init__(self, a):
>     self.a=a
>   def __call__(self):
>     b, self.a=self.a, self.a+1
>     return b
>

Just use a Python 2.2 construct, and you're up and running with a (sorta) 
lexical closure (its just as the name states a generator, but you can use it 
to construct a lexical closure).

Try the following:

# Needs Python 2.2a1 (at least)

from __future__ import generators

# At the point of yield, all values are stored and a generator object is
# returned to the main program on the first run (after startvalue and endvalue
# have been pumped into the function). This generator object can now be used
# just like an iterator.

def hello(startvalue=1234,endvalue=5678):
    for i in range(startvalue,endvalue):
        yield i

# We store the generator object in gen.

gen = hello(5,105)

# We get the next value 100 times. (thus writing 5-104 on the screen, and
# exhausting the generator)

for x in range(1,101):
    print gen.next()

# The next prints a StopIteration exception, because the generator fell over
# the end of the function.

print gen.next()

Hope this helps! I think generators are even more useful than lexical 
closures! :)

-- 
Yours sincerely,

	Heiko Wundram




More information about the Python-list mailing list