Importing from a file to use contained variables

Francis Avila francisgavila at yahoo.com
Sun Nov 30 02:19:17 EST 2003


Jeff Wagner wrote in message ...
>On 29 Nov 2003 21:04:25 GMT, bokr at oz.net (Bengt Richter) wrotf:
>
>What is a generator maker?


My advice is not to play around with this until you get the basics down,
because generators and generator functions embody a number of very advanced
concepts.

I make it sound scary, but really all it is is this:

def count():  #Defines a generator factory.
    n = 0
    while n < 10:
        yield n
        n += 1

mycounter = count() #Gets a generator instance from the factory.

mycounter.next()  # returns 0.

for i in mycounter: print i, # prints "1 2 3 4 5 6 7 8 9"

Generators are a strange mix of functions and classes: using the 'next'
method of a generator, execution advances to the next "yield" statement,
where it then "returns" whatever's to the right of the 'yield'.  When the
generator hits a real or implied 'return', it raises a StopIteration
exception, and stops for good.

The 'for' statement and other things like list() all use these next() and
StopIteration things implicitly.  This behavior is part of the "generator
protocol", and anything that implements it can be used as a generator.

Generators are nifty because they are very fast, use very few resources, and
can make many complex state-related problems easier to code.  They're
relatively new to Python--few languages have anything like them at all.
They're not a must-have, but they are very useful.

Now stay away from them until you know what you're doing. ;)
--
Francis Avila





More information about the Python-list mailing list