Every Python service that spends its life waiting on the network eventually meets the same wall. You need to hold a few thousand slow connections open, or fan out requests to hundreds of endpoints, and the obvious tools stop cooperating. Threads cost roughly a stack apiece and the scheduler starts thrashing long before you reach the counts your users demand. The modern answer — async/await — works, but it is contagious: once one function becomes a coroutine, the entire call chain above it must be rewritten, and half the libraries you depend on simply do not speak that dialect.
gevent has always taken the opposite bet. Instead of asking you to color your code with async and await, it keeps your functions perfectly synchronous and changes what “blocking” means underneath. A read from a socket parks the current greenlet, hands control to an event loop, and resumes the greenlet when data arrives — so ordinary, unmodified, synchronous code scales like an event-driven server. The magic that makes this work with libraries you did not write is monkey patching: replace the CPython standard library modules for sockets, threads, and selectors with cooperative equivalents, and the whole ecosystem follows.
This post is a source tour of the gevent repository on its master branch, at version 26.9.1.dev0 (the changelog shows 26.9.0 shipped on 2026-09-16). We walk the real tree: the hub that never returns, the monkey package, the single base class shared by every synchronization primitive, the pool layer, and the Cython accelerator modules that keep the fast path fast. Every symbol and line number below was verified against the actual checkout.
The overview map of gevent: monkey patching feeds the public API, the public API hangs off a per-thread Hub, every primitive inherits one linkable base, and the Hub drives the libev loop while sockets wait on its watchers.
Reading the overview from left to right:
- patch_all, L640 — the one-call entry point whose defaults patch socket, dns, time, select, thread, os, ssl, subprocess, builtins, signal, queue, and contextvars; only
sysdefaults to False. - spawn = Greenlet.spawn, L77 — the top-level
gevent.spawnis literally a classmethod alias, next to__version__at line 30. - get_hub, L79 — returns the current thread’s hub, creating it on first use with
_threadlocal.hub = hubtype()at line 106. - Hub, L373 —
class Hub(WaitOperationsGreenlet), the greenlet that runs the event loop for one thread. - Hub.run, L631 — an infinite
while 1: loop.run()whose docstring warns the method “must never return”. - spawn_raw, L70 — the low-level spawner whose comment states “The hub is always the parent”, scheduling with
loop.run_callback(g.switch)at line 121. - Greenlet, L177 — the full-featured subclass; its
spawnclassmethod at line 679 is justg = cls(*args, **kwargs); g.start(). - Semaphore, L48 — inherits
AbstractLinkable, like Event and AsyncResult; BoundedSemaphore follows at line 470. - loop, L405 —
cdef public class loop, the libev backend compiled from Cython withrunat line 619 andrun_callbackat line 745.
The detail map zooms into modules: the greenlet-to-hub inheritance chain, the linkable base shared by Event, AsyncResult and Semaphore, how pools spawn greenlets, and how the build compiles core modules to C.
The hub is a greenlet that never returns
The design decision that explains most of gevent is in hub.py, a 909-line module: the event loop is not a component the library calls — it is a greenlet the library switches to. Hub extends WaitOperationsGreenlet (defined at line 44 of src/gevent/_hub_primitives.py), which extends SwitchOutGreenletWithLoop (line 54 of src/gevent/_greenlet_primitives.py), which extends TrackedRawGreenlet (line 35 of the same file). So every hub is a real greenlet.greenlet with a loop attached, and every user greenlet’s parent is that hub — spawn_raw constructs its greenlet with the hub as parent and schedules its first execution via loop.run_callback(g.switch).
Hub.run at line 631 is almost anticlimactic: assert you are the current greenlet, start the periodic monitoring thread, then while 1: around loop.run(). The docstring is blunt — the method must never return, because returning would make switches into the hub deliver unexpected values. If the loop ever finishes because nothing is scheduled and no watchers are active, run() raises LoopExit, which the source describes as possibly indicating a programming error. There is no third path.
Because the hub is per-thread, src/gevent/_hub_local.py keeps it in a thread local: get_hub checks _threadlocal.hub and lazily constructs one of the class returned by get_hub_class. Interestingly, the cooperative switch interval is borrowed from the interpreter itself — src/gevent/__init__.py at lines 68-69 assigns getswitchinterval = sys.getswitchinterval, so gevent respects the same knob the runtime already exposes.
Monkey patching, packaged
The patching surface is no longer one enormous module: src/gevent/monkey/ is a package, with the 759-line __init__.py hosting the docstrings and patch_all. Its signature at line 640 spells out the entire surface area: socket, dns, time, select, thread, os, ssl, subprocess, builtins, signal, queue, and contextvars all default to True, sys defaults to False, and aggressive controls whether DNS calls are forced through the resolver. The docstring documents the sharp edges honestly — patching twice with different arguments only ever adds patches, never removes them — and warns that a future release planned for early 2027 will make all arguments keyword-only.
Two helpers make the machinery survivable. get_original in src/gevent/monkey/api.py (line 10) hands back the pre-patch implementation of any standard library attribute, so your code can reach the real socket when it genuinely needs it. And the whole thing is scriptable: src/gevent/monkey/_main.py defines main() at line 8, which backs python -m gevent.monkey — you can patch an unmodified script from the command line without editing a single line of it.
From pure Python to Cython accelerators
The build system is where gevent quietly spends its performance budget, and it is unusual enough to deserve its own numbers. setup.py (477 lines) lists thirteen modules in _to_cythonize at lines 142-158 — the greenlet and hub primitives, the hub itself, greenlet.py, the abstract linkable, the semaphore, local.py, ident, imap, event, and queue. These are ordinary .py files compiled by Cython into C extension modules with names like gevent._gevent_c_semaphore: the definition at lines 66-69 sets sources=["src/gevent/_semaphore.py"] with a companion _gevent_c_semaphore.pxd declaring the C-level attributes. The Python file remains the source of truth; the .pxd files (twelve of them, named _gevent_c*.pxd) exist so compiled modules can share declarations. In total EXT_MODULES at lines 160-176 carries fifteen entries, including the libev core and the optional c-ares resolver, plus two cffi modules for the libev and libuv backends — with an honest comment explaining why the libev CFFI build is skipped on Windows: the needed libev_vfd.h calls Python API functions from CFFI code, which is forbidden there.
The payoff of all this is that the hot switching path — waiter switches, semaphore accounting, queue wakes — runs as C while still being maintained as readable Python. The core module src/gevent/libev/corecext.pyx (1,455 lines) declares cdef public class loop at line 405, and its run (line 619) and run_callback (line 745) are what Hub.run drives. The scale of the pure-Python surface is also worth knowing: greenlet.py is 1,204 lines, pywsgi.py is 1,731, and queue.py is 826.
One linkable base for every primitive
Open any synchronization primitive in gevent and you find the same parent: AbstractLinkable, defined at line 72 of src/gevent/_abstract_linkable.py (611 lines). Event (line 26 of event.py), AsyncResult (line 175 of the same file), and Semaphore (line 48 of _semaphore.py) all inherit from it. The base implements the callback-link machinery — link, unlink, and the _check_and_notify method at line 227 — and the notify path is revealing: line 267 schedules the link notifications with hub.loop.run_callback(...), so even primitive wakeups ride the loop rather than running inline on the waking thread. Timeout is the odd one out — it extends BaseException (line 72 of timeout.py) precisely so it can be raised through arbitrary frames, and with_timeout at line 382 wraps any call in that behavior.
Queues are built from the same parts. Queue sits at line 490 of queue.py, and its handoff between producers and consumers goes through ItemWaiter(Waiter) at line 94 — the same Waiter.switch (line 105 of _waiter.py) the hub uses to resume parked greenlets. Channel, the one-slot primitive, is strict about it: constructing one with a maxsize other than 1 raises ValueError. Higher up, lock.py contributes RLock at line 275 and a DummySemaphore for no-op contention.
Pools and the network stack
pool.py (677 lines) layers resource management over greenlets. Group at line 283 tracks a set of running greenlets; Pool extends it at line 520 with a size limit, and when that limit is hit it raises PoolFull — defined at line 513 as a subclass of QueueFull, deliberately reusing the queue exception hierarchy. Submitting work is just spawning: apply_async returns Greenlet.spawn(self.apply_cb, ...) at line 133, and the imap method at line 229 returns an IMap iterator backed by IMapUnordered(Greenlet) from src/gevent/_imap.py line 43.
The network stack is a facade over a facade. src/gevent/socket.py is only 166 lines: it pulls everything from src/gevent/_socket3.py with copy_globals at line 39 and adds a careful create_connection. The real socket class lives at line 89 of _socket3.py as socket(_socketcommon.SocketMixin), and the shared module provides cancel_wait (line 168) plus the DNS entry points that make the resolver pluggable. Servers then compose on top: StreamServer at line 34 of server.py, DatagramServer at line 213, and the 1,731-line pywsgi.py whose WSGIServer(StreamServer) at line 1526 gives you a production-shaped WSGI container. The classic pairing — monkey-patch the process, then throw a fleet of blocking requests calls at it — still works because every layer below now parks greenlets instead of threads.
Honest Limits
Monkey patching remains a global, order-sensitive operation: the docs of Enjoyed this post? Never miss out on future posts by following us patch_all warn that subsequent calls can only add patches, never remove them, and that mixing patched and unpatched modules can leave you with subtly inconsistent state. The keyword-only migration announced for early 2027 will break positional callers like patch_all(True, True, False). The hub’s contract is unforgiving by design — Hub.run must never return, and LoopExit is a real possibility for programs that spawn nothing and wait on nothing, which can look like a crash when it is actually a diagnosis. Channel locks its maxsize to 1 by construction. The libev CFFI backend is not built on Windows, so that platform rides the compiled extension or libuv. And the version we toured, 26.9.1.dev0, is a development snapshot; the last stable release was 26.9.0 on 2026-09-16, so verify the tree you pin against.