I'm super late to this party but I was interested from a historical perspective what this decorator did.
The accepted answer is simply wrong, or really a non-sequitur, and editing it would be an entire re-write so better to leave it and answer separately.
For the OPs example, what @asyncio.coroutine
did was attach the CO_ITERABLE_COROUTINE
flag to the object's co_flags
. This allowed the generator to be used with the await
keyword and also to yield from
"pure" coroutines that were not themselves generator-derived.
# Check if 'func' is a generator function.
# (0x20 == CO_GENERATOR)
if co_flags & 0x20:
# TODO: Implement this in C.
co = func.__code__
func.__code__ = CodeType(
co.co_argcount, co.co_posonlyargcount, co.co_kwonlyargcount, co.co_nlocals,
co.co_stacksize,
co.co_flags | 0x100, # 0x100 == CO_ITERABLE_COROUTINE
co.co_code,
co.co_consts, co.co_names, co.co_varnames, co.co_filename,
co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars,
co.co_cellvars)
return func
The decorator had some other uses, notably (as illustrated in the accepted answer), it would transform a regular function into a coroutine if it was not already a generator.
async def
andawait
syntax wasn't available until 3.5 whileasyncio
was formally introduced in 3.4... – Cygnusasyncio.coroutine
decorator add to my code? I can use thegenerator
as acoroutine
without additional code right. [My next question is why do we need theasync def
andawait
as a syntax when it can be achieved without that. But I will not mix that with this question.] – Midwifecoroutine
is, it doesn't needasyncio
. So when we decorate acoroutine
withasyncio.coroutine
do we add some value to it? For exampleTwisted
sinlineCallbacks
decorator can be used to trigger and run a coroutine till it ends. Something like it accepts agenerator function
, executes it to get thegenerator object
... Then starts it withNone
etc. – Midwifeasyncio
IO as a base for doing the same thing (without all the ready made reactors and protocols)... Might be worth having a read through a tutorial or basic examples of it and take it from there... – Cygnusasync def
starting in 3.5. – Havildarasyncio/coroutines.py
). It seems like documentation and explanations are more clear after looking at the code (it's like the code is documenation for the explanations...). – Duff