On this page
  1. selectors
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Event-Loop Dispatch Using key.data Callbacks
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects
  10. Constants & Attributes

selectors

Prev: select | Up: stdlib_module | Next: shelve
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — selectors
Tags: #public #python3 #stdlib


Import

import selectors

Overview

High-level, portable I/O multiplexing built on top of select (DefaultSelector, EVENT_READ, EVENT_WRITE). Automatically chooses the best OS backend (KqueueSelector on macOS/BSD, EpollSelector on Linux, SelectSelector on Windows) and lets you attach callback or state metadata directly to each registered file object.

Quick Start

import selectors
import socket

s1, s2 = socket.socketpair()
try:
    with selectors.DefaultSelector() as sel:
        sel.register(s2, selectors.EVENT_READ, data="peer-2")
        s1.sendall(b"hi")
        events = sel.select(timeout=1.0)
        assert len(events) == 1 and events[0][0].data == "peer-2"
        assert s2.recv(2) == b"hi"
finally:
    s1.close()
    s2.close()

Implementation Walkthrough

1. Event-Loop Dispatch Using key.data Callbacks

Attach a handler callable to data= on register() so the loop dispatches cleanly without maintaining separate lookup dicts:

import selectors

def run_once(sel: selectors.BaseSelector, timeout: float = 0.5) -> int:
    handled = 0
    for key, mask in sel.select(timeout=timeout):
        callback = key.data
        callback(key.fileobj, mask)
        handled += 1
    return handled

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes