Python generators (coroutines)

Jean-Paul Calderone exarkun at divmod.com
Wed Apr 23 20:26:44 CEST 2008


On Wed, 23 Apr 2008 10:53:03 -0700 (PDT), Michele Simionato <michele.simionato at gmail.com> wrote:
>On Apr 23, 4:17 pm, rocco.ro... at gmail.com wrote:
>> I would really like to know more about python 2.5's new generator
>> characteristics that make them more powerful and analogous to
>> coroutines. Is it possible for instance to employ them in situations
>> where I would normally use a thread with a blocking I/O (or socket)
>> operation? If it is, could someone show me how it can be done? There
>> appears to be a very limited amount of documentation in this repect,
>> unfortunately.
>>
>> Thank you.
>
>The real changes between Python 2.4 and Python 2.5 generators are
>1) now you can have a yield inside a try .. finally statement
>2) now you can send an exception to a generator
>
>The fact that now you can send values to a generator
>is less important, since you could implement the
>same in Python 2.4 with little effort (granted, with an uglier syntax)
>whereas there was no way to get 1) and 2).
>Anyway, if you have a blocking operation, the only solution is to use
>a thread or a separate process.

You could have #2.  It's a trivial variation of sending a value.  For
example,

http://twistedmatrix.com/trac/browser/trunk/twisted/internet/defer.py#L555

Jean-Paul



More information about the Python-list mailing list