7

I know I must be missing something simple, but I am not seeing it.

If I have a generator expression like this:

>>> serializer=(sn for sn in xrange(0,sys.maxint))

I can generate, easily, individual integers like this:

>>> serializer.next()
0
>>> serializer.next()
1
>>> serializer.next()
2

If I write a generator like this:

>>> def ser():
...    for sn in xrange(0,100000):
...       yield sn

It is no bueno:

>>> ser().next()
0
>>> ser().next()
0
>>> ser().next()
0

??? What am I missing ???

3 Answers 3

21

ser() creates the generator. So each time you call ser() it is sending you a new generator instance. You need to use it just like the expression:

serializer = ser()
serializer.next()

Consider that, if it didn't work this way, you could only ever use the ser() function once and you could never reset it. Plus, you can change the ser function to accept a max integer, and make your program more flexible.

def ser(n=sys.maxint):
    for sn in xrange(0, n):
        yield sn
1
  • 2
    no problem. it's definitely non-obvious, since the other major type of functions that do this (decorators) have an explicit return wrapper in them, which I guess is implicit/magically created by the yield statement :P Jun 9, 2012 at 6:14
5

In your second example you keep creating a new instance, starting with a fresh generator.

g = ser()
g.next()
g.next()

Create the generator once and reuse it.

4
ser()

initializes a new generator each time.

To fix it do something like this:

s = ser()
next(s) # next is preferred over .next which is why .next has been removed in Py3
next(s)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.