The problem is: writer.close() is a regular method which calls transport.close().
But transport.close() actually closes the connection only on next loop iteration by self._loop.call_soon(self._call_connection_lost, None) call`.
Now a safe way for stream closing is
writer.close()
await sleep(0)
but it looks ugly.
I see two possible solutions:
- Introducing
writer.wait_closed() coroutine.
- Changing
writer.close() signature to return a future object. The future will be resumed on protocol's connection_lost() callback.
Honestly I vote on point 2: it looks more native and fully backward compatible with existing code.