eladm26
eladm26

Reputation: 563

python asyncio Transport asynchronous methods vs coroutines

I'm new to asyncio and I started working with Transports to create a simple server-client program.
on the asyncio page I see the following:

Transport.close() can be called immediately after WriteTransport.write() even if data are not sent yet on the socket: both methods are asynchronous. yield from is not needed because these transport methods are not coroutines.

I searched the web (including stackoverflow) but couldn't find a good answer to the following question: what are the major differences between an asynchronous method and a coroutine?
The only 2 differences I can make are:

  1. in coroutines you have a more fine grained control over the order of the methods the main loop executes using the yield from expression.
  2. coroutines are generators, hence are more memory efficient.

anything else I am missing?

Thank you.

Upvotes: 2

Views: 344

Answers (1)

Andrew Svetlov
Andrew Svetlov

Reputation: 17366

In the context asynchronous means both .write() and .close() are regular methods, not coroutines.

If .write() cannot write data immediately it stores the data in internal buffer.

.close() never closes connection immediately but schedules socket closing after all internal buffer will be sent.

So

transp.write(b'data')
transp.write(b'another data')
transp.close()

is safe and perfectly correct code.

Also .write() and .close() are not coroutines, obviously. You should call coroutine via yield from expression, e.g. yield from coro().

But these methods are convention functions, so call it without yield from as shown in example above.

Upvotes: 3

Related Questions