pyfect lets you write Python programs whose type says what they return, how they can fail
and which services they need, so pyright rejects a program that forgets to handle an error
or provide a dependency. It is for Python developers building services, pipelines and CLIs
who want Effect's model (typed errors, structured concurrency, layers, streams, schema)
without leaving Python.
A quick look
from dataclasses import dataclass
from typing import Protocol
import pyfect as fx
from pyfect import layer
class UserStore(Protocol):
def find(self, user_id: str) -> fx.Effect[str | None]: ...
class Users(fx.Tag[UserStore]): ...
class InMemoryUsers:
def find(self, user_id: str) -> fx.Effect[str | None]:
return fx.succeed({"1": "Ada"}.get(user_id))
@dataclass
class UserNotFound(fx.TaggedError):
user_id: str
@fx.fn
def greet(user_id: str):
users = yield from Users()
name = yield from users.find(user_id)
if name is None:
return (yield from UserNotFound(user_id))
return f"Hello, {name}!"
# greet("1") is inferred as Effect[str, UserNotFound, Users]
program = (
greet("1")
.pipe(fx.catch_tag(UserNotFound, lambda e: fx.succeed("Who?")))
.pipe(fx.provide(layer.succeed(Users, InMemoryUsers())))
)
print(fx.run_blocking(program)) # Hello, Ada!
Remove the catch_tag line and pyright stops you before the program runs:
error: Argument of type "Effect[str, UserNotFound, Never]" cannot be assigned to
parameter "eff" of type "Effect[A@run_blocking, Never, Never]" in function "run_blocking"
"Effect[str, UserNotFound, Never]" is not assignable to "Effect[str, Never, Never]"
Type parameter "E_co@Effect" is covariant, but "UserNotFound" is not a subtype of "Never"
Type "UserNotFound" is not assignable to type "Never" (reportArgumentType)
That covers the errors an effect fails with, as greet does with yield from UserNotFound(...).
An exception you raise is a defect, which the type doesn't track
(Errors).
examples/quickstart.py builds on this with a resource-managed
layer, concurrency, retries and timeouts.
How it works
- Describe. A generator decorated with
@fx.fn builds an Effect[A, E, R]: a value
that describes the work. Nothing runs yet, and pyright infers all three types with no
annotations.
- Narrow. Each handler removes exactly the error it handles, and each layer removes
exactly the services it builds. The type shrinks as you go.
- Run. Only an effect with no errors and no services left can run. pyfect runs it on
its own fiber scheduler, synchronously or on asyncio, with structured concurrency and
interruption that always runs finalizers.
Features
Core runtime
- Typed errors: expected failures live in the type, defects stay separate; take results apart with
match, or raise every error at once as an ExceptionGroup for except*. Errors →
- Services and layers: dependency injection pyright checks, with memoized layers that release in order. Services →
- Its own fiber runtime:
run_blocking with no event loop, or on asyncio; blocking moves calls to a thread. Effects →
- Structured concurrency: children end with their parent,
all and for_each take a limit, races clean up. Concurrency →
- Resources: scopes,
acquire_release, pools, RcRef and RcMap release exactly once, even on interruption, and with fx.managed(...) holds one in plain Python code. Resources →
- Parallel work:
fx.on_thread runs an effect on a thread of its own, in parallel on free-threaded Python, and interpreter_pool runs pure functions in subinterpreters on several cores. Parallel effects → · Subinterpreters →
- Retries and schedules: exponential, jittered, cron and composed schedules for
retry and repeat. Schedules →
- Streams: pull-based streams, sinks and channels with backpressure, plus NDJSON and SSE framers. Streams →
- Transactions: software transactional memory with
TxRef, queues, maps, locks and semaphores. Transactions →
Data
- Schema: decode and encode with Effect's messages, schemas from type annotations (a schema or checks in
Annotated included), compiled decoders, JSON Schema, Hypothesis, pydantic and msgspec. Schema →
- Config: typed settings from the environment,
.env files or dicts, with secrets kept out of logs. Config →
- Graphs: directed and undirected graphs with walks, shortest paths, flows, matchings and Mermaid output. Graphs →
- Cryptography: random ids, digests, encryption, signatures and JOSE tokens, as services. Cryptography →
Web, APIs and AI
- Platform: files, child processes, an httpx HTTP client and TCP, TLS, WebSocket and UDP sockets, all swappable in tests. Platform →
- HTTP server: routes and middleware added by layers, served by the standard library, uvicorn, hypercorn (HTTP/2) or any ASGI server. HTTP server →
- HttpApi: declare an API once with schemas; serve it, call it with a derived client, document it with OpenAPI. HttpApi →
- RPC: typed procedures over HTTP, WebSockets, stdio or workers, with streamed results and a test client. RPC →
- GraphQL: typed queries, mutations and subscriptions over HTTP, SSE or WebSockets, with batched lookups. GraphQL →
- CLI: typed commands, flags and arguments with subcommands, help, shell completions and prompts. CLI →
- Atoms: reactive values with derived, effect, stream and RPC atoms, and server-to-client hydration. Atoms →
- AI: a provider-neutral
LanguageModel with structured output, typed tools and chats, on Anthropic, OpenAI, OpenRouter and more. AI →
- MCP: serve a toolkit over the Model Context Protocol on HTTP or stdio, and call any MCP server's tools. MCP →
Testing and observability
- Deterministic tests: a pytest plugin with a virtual clock, so a test of a 30-second retry takes no real time. Testing →
- Observability: logging, spans and metrics, exported over OTLP or through the OpenTelemetry SDK, and a profiler that times each fiber. Observability →
- SQL: statements from literal templates, so values are always bound parameters; transactions, migrations and seven dialects. SQL →
- Models: one class for a row and its insert, update and JSON variants, with typed repositories. Models →
- Persistence: key-value stores, persisted caches and durable at-least-once queues in memory, files, SQL or Redis. Persistence →
- Rate limiting and circuit breakers: per key, in memory or shared through Redis, and HTTP clients that obey rate limit headers. Rate limiting →
- Workers: run code on threads or in child processes, by messages or typed RPC over a pool. Workers →
- Workflows: durable steps whose results are stored and replayed, with durable sleeps, waits completed from outside and compensation. Workflows →
- Event log: events in a local journal, replayed through handlers and synced with a server, optionally end-to-end encrypted. Event log →
- Cluster: sharded stateful entities, cluster-wide singletons and cron jobs, and workflows that resume on another runner. Cluster →
Parity with Effect
pyfect follows Effect 4.1.2, does what Effect does wherever Python can express it, and runs
Effect's own test cases as its spec: over 37,000 tests, with a test that fails on any Effect
test title neither ported nor omitted with a reason. It covers about 95% of Effect v4 (about 94% of the runtime core) so far. Every
export of the core modules is listed against Effect's in docs/coverage/, and
docs/PARITY.md tracks what is done, what is open and what still differs.
Installation
pyfect needs Python 3.13 or later. Install the pyfect-dev distribution from PyPI and
import pyfect (PyPI's pyfect is an unrelated project).
uv init --python 3.14+gil app && cd app # a new project; skip in one that has a [project] table
uv add pyfect-dev
uv add --dev pyright
With pip, in a virtual environment of Python 3.13 or later: pip install pyfect-dev pyright.
3.14+gil needs uv 0.9.8 or later. Installation covers older uv and Python versions, the optional extras and pyright's settings.
Learn more
- Documentation: guides for each part of the library.
- API reference: every public function and class.
- Changelog: what each release changed.
- Examples, all checked by pyright: a quickstart, request batching,
a CLI, a FastAPI-style service, a typed HTTP API, an MCP server, schema decoding, a stream
pipeline and a durable workflow.
- Effect's docs: the concepts carry over; pyfect uses
snake_case and
yield from in place of yield*.
Contributing
Contributions are welcome. CONTRIBUTING.md covers setup, the one
command that checks everything, and how a change is ported from Effect. Issues labelled
good first issue are a
good place to start. Everyone taking part agrees to the
Code of Conduct.
License
MIT. pyfect is an independent port and is not affiliated with Effectful
Technologies; Effect is MIT-licensed by its authors.