A protocol factory is a callable that creates a new protocol instance for a connection. asyncio connection APIs invoke it, then return the created protocol alongside the transport. section 8.2 section 8.4
The factory keeps connection setup separate from protocol construction. For an HTTP client, it can capture the host and event loop, create HTTPGetClientProtocol, and let create_connection establish the connection. section 8.2
Creating an HTTP protocol
Define a local factory, pass it to loop.create_connection, and retain the returned protocol when its response coroutine is needed: def protocol_factory(): return HTTPGetClientProtocol(host, loop); _, protocol = await loop.create_connection(protocol_factory, host=host, port=port). section 8.2
The same pattern connects standard input to a StreamReader. StreamReaderProtocol wraps the reader, while a factory returns that protocol to connect_read_pipe; readline then provides asynchronous input. section 8.4
Asynchronous standard input
Create a StreamReaderProtocol around a StreamReader and return it from the factory: await loop.connect_read_pipe(lambda: protocol, sys.stdin). The resulting reader supports await stdin_reader.readline(), allowing delay tasks to continue while input is read.
