Saturday, April 29, 2017

a return to yield

I remember when, almost a decade ago, I was first discovering generators. It was a heady time, and I saw applications everywhere.

def fib_gen():
    x, y = 1, 1
    while x < 100:
       x, y = y, x + y
       yield x
    return

I also remember the first time I tried to mix a return value into my generator.

def fib_gen():
    x, y = 1, 1
    while x < 100:
       x, y = y, x + y
       yield x
    return True

Imagine my surprise, as I'm sure countless others experienced as well:

SyntaxError: 'return' with argument inside generator
A rare compile-time error! Only the decorative, bare return is allowed in generators, where they serve to raise StopIteration.

Now, imagine my surprise, so many years later when I import that same code in Python 3.


...

Nothing! No error. So what happened?

Turns out that the coroutine and asyncio machinery of Python 3 has repurposed this old impossibility.

If we manually iterate to skip over our yield:

fib_iter = fib_gen()                                                                                                                                                                                                    
for i in range(11):                                                                                                                 
    next(fib_iter)                                                                                                                  
next(fib_iter)

We see what's really happening with our return:

Traceback (most recent call last):
  File "fib_gen.py", line 13, in <module>
    next(fib_iter)
StopIteration: True

That's right, returns in generators now raise StopIteration with a single argument of the return value.

Most of the time you won't see this. StopIterations are automatically consumed and handled correctly by for loops, list comprehensions, and sequence constructors (like list). But it's yet another reason to be extra careful when writing your own generators, specific to Python 3.

13 comments:

  1. I have gone through most of your posts. This post is probably where I got the most useful information for my work. Thanks for posting, are you aware of custom essay writing service? Try to use this one for your writing work; definitely you can see the result.

    ReplyDelete
  2. Nice post I gained lots of thing through this blog My sincere thanks for sharing this valuable post
    Python Training in Chennai

    ReplyDelete
  3. Great articles, first of all Thanks for writing such lovely Post! Earlier I thought that posts are the only most important thing on any blog..
    Python Training in Bangalore |
    Software Testing Training in Bangalore

    ReplyDelete

  4. hello everyone.....
    thank the good topic.
    Welcome To Casino online Please Click the website
    thank you
    บาคาร่า
    จีคลับ
    gclub

    ReplyDelete
  5. I really appreciate the information shared above. It’s of great help. If someone wants to learn Online (Virtual) instructor lead live training in Python TECHNOLOGY, kindly contact us http://www.maxmunus.com/contact
    MaxMunus Offer World Class Virtual Instructor-led training on TECHNOLOGY. We have industry expert trainer. We provide Training Material and Software Support. MaxMunus has successfully conducted 100000+ pieces of training in India, USA, UK, Australia, Switzerland, Qatar, Saudi Arabia, Bangladesh, Bahrain and UAE etc.
    For Demo Contact us.
    Pratik Shekhar
    MaxMunus
    E-mail: pratik@maxmunus.com
    Ph:(0) +91 9066268701
    http://www.maxmunus.com/

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. This article is about integrating gun safety courses into our nations educational system for grades K - 12. The overall goal would be to provide more safe learning environment where students are able to develop a lifelong set of skills and knowledge.http://www.careerpanth.xyz/

    ReplyDelete
  8. Thanks for providing this good information,Thanks for your sharing.
    goldenslot
    gclub online
    gclub casino

    ReplyDelete
  9. Take a look at this interesting essay writing adviceэы

    ReplyDelete
  10. Has anyone got any comments about the post that aren't just ads for something else? Just wondering.

    ReplyDelete
  11. Your website is really nice and this is a great inspiring article.

    goldenslot
    Gclub จีคลับ

    ReplyDelete