erikkaplun / txcoroutine

Fuller coroutine support for Twisted than inlineCallbacks + memory efficient tail call optimization
BSD 2-Clause "Simplified" License
9 stars 2 forks source link

More intuitive coroutine exit #2

Open andreikop opened 10 years ago

andreikop commented 10 years ago

In your examples you use next piece of code:

finally:  # could use `except GeneratorExit` but `finally` is more illustrative

I would say, that finally is also not very illustrative. How about adding exception CouroutineCancelled to the txcoroutine API and throwing it to generator function with http://docs.python.org/2/reference/expressions.html?highlight=throw#generator.throw? So, couroutine would look this way:

  @coroutine
  def do_job()
    try:
      while True:
        yield do_something()
    except CoroutineCancelled:
      print 'Done!'

You may also create alias CoroutineCancelled for GeneratorExit in your library, and continue using generator.close(). In this case existing code, which uses txcoroutine, will not be broken.

Thanks for the cool library!

erikkaplun commented 10 years ago

I'm glad to see somebody is finding the library useful! :)

However, can you please elaborate a bit on the purpose of such change? What would this CoroutineCancelled exception add to the picture? What could you do that you cannot do now?

Let me also point out that finally: is not the same as except GeneratorExit:—the former will be executed no matter what; exept GeneratorExit only when GeneratorExit is raised.

andreikop commented 10 years ago

All works fine. This is only about code readability.

You are right, that finally and except GeneratorExit is not the same. I use except .. to write logs 'Process finished successfully'. But, catching GeneratorExit looks not intuitive, I'm not sure if new guys who haven't read your post about @coroutine would understand this code.