liveBook · Manning

Protocol factory

As explained in Python Concurrency with asyncio

A protocol factory is a callable that creates and returns a protocol instance for a connection.

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.

How Python Concurrency with asyncio covers it

How deep it goes
Defines the callable and demonstrates two practical integrations, but defers lower-level protocol internals and higher-level streams.
Examples
Uses an HTTP client connection and an asynchronous standard-input reader with concurrent delay tasks.
What it assumes
Assumes basic asyncio coroutines and introduces the relationships among event loops, transports, protocols, pipes, and stream readers.
What you can do after
Apply it via asyncio to construct connection-specific protocols for network requests or asynchronous pipe input.
How it connects
Ties protocol factories to asyncio event loops, transports, protocols, streams, StreamReader, and standard input.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.