pyfect
Effect for Python. Errors, dependencies and concurrency checked by pyright.
Read the docs · Install · Examples · Parity with Effect · Contribute
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())))
)
fx.run_blocking(program)
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]"
Type "UserNotFound" is not assignable to type "Never"
examples/quickstart.py builds on this with a resource-managed
layer, concurrency, retries and timeouts.
How it works
- Describe. A generator decorated with
@fx.fnbuilds anEffect[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
- Typed errors. Expected failures live in the type;
catch_taghandles one, and defects stay separate. Errors → - Services and layers. Dependency injection checked by the type checker, with memoized, concurrently built layers that release their resources in order. Services →
- A fiber runtime of its own. The same program runs with
run_blocking(no event loop) or on asyncio.blockingmoves blocking calls to a thread. Effects → - Structured concurrency. Children end with their parent;
allandfor_eachtake a concurrency limit; races wait for losers to clean up. Concurrency → - Resources. Scopes,
acquire_release, pools,RcRefandRcMaprelease exactly once, even on interruption. Resources → - Retries and schedules. Exponential, jittered, cron and composed schedules for
retryandrepeat. Schedules → - Streams. Pull-based streams, sinks and channels with backpressure, plus NDJSON, JSON array and Server-Sent Events framers. Streams →
- Schema. Decode and encode data with Effect's error messages, compile decoders at run time or ahead of time, generate JSON Schema and Hypothesis strategies, store schemas themselves as JSON documents, and plug into Standard Schema, pydantic or msgspec. Schema →
- Transactions. Software transactional memory:
TxRef, transactional queues, maps, locks and semaphores that commit atomically and retry without blocking a thread. Transactions → - Graphs. Directed and undirected graphs with stable indexes: walks, shortest paths, components, flows and matchings, GraphViz and Mermaid output, and a schema for storing them as JSON. Graphs →
- Cryptography. Secure random ids, digests, authenticated encryption, signatures and key formats as services, and signed or encrypted JOSE tokens on top of them. Cryptography →
- Config. Typed settings from the environment,
.envfiles or dicts, with secrets kept out of logs. Config → - Observability. Logging, spans and metrics, exported through Effect's own OTLP exporters or the OpenTelemetry SDK. Observability →
- Platform. Files, child processes, an HTTP client (httpx), an HTTP server (standard library, uvicorn, hypercorn for HTTP/2, or any ASGI server), and TCP, TLS, WebSocket and UDP sockets, all as services you can swap in tests. Platform →
- SQL. Statements built from literal templates, so values are always bound parameters; transactions with savepoints, batching resolvers and migrations, on SQLite (standard library), PostgreSQL (psycopg), MySQL (asyncmy), SQL Server (python-tds), libSQL and Turso, ClickHouse and Cloudflare D1 (the last three over HTTP). SQL →
- CLI. Typed commands, flags and arguments with subcommands, generated help, shell completions and interactive prompts. CLI →
- HTTP server. Routes and middleware added by layers, each handler an effect, served on uvicorn or as an ASGI app. HTTP server →
- HttpApi. Declare an API once with schemas, then serve it, call it with a derived client and document it with OpenAPI and Swagger UI. HttpApi →
- RPC. Typed procedures over HTTP, WebSockets or workers (threads and child processes), with streamed results and an in-memory test client. RPC →
- Persistence. Key-value stores, caches whose results outlive the process and durable at-least-once queues, in memory, files, SQL or Redis. Persistence →
- Rate limiting and circuit breakers. Limits and breakers per key, in memory or shared by every process through Redis, and HTTP clients that follow a server's rate limit headers. Rate limiting →
- Workers. Run code on threads or in child processes and talk to it by messages or typed RPC calls over a pool. Workers →
- Workflows. Durable workflows whose steps run once and are replayed, with durable sleeps, waits completed from outside and compensation on failure. Workflows →
- AI. A provider-neutral
LanguageModelfor text, structured output, streaming and typed tools, chats that keep their history, typed decisions (classify, rate, probability), and Anthropic, OpenAI, OpenAI-compatible, OpenRouter, Cloudflare and TypeSafe providers over the HTTP client. AI → - MCP. Serve a toolkit over the Model Context Protocol on HTTP or stdio, and call any MCP server's tools. MCP →
- Models. One class for a table's row and its insert, update and JSON variants, with typed repositories on any SQL client. Models →
- GraphQL. Typed queries, mutations and subscriptions over HTTP, Server-Sent Events or WebSockets, with middleware, pagination and batched lookups. GraphQL →
- Event log. Events written to a local journal, replayed through handlers and synced with a server, encrypted end to end if you like. Event log →
- Cluster. Stateful entities sharded over runners that talk over TCP, HTTP or WebSockets, with messages and shard locks in SQL, singletons and cron jobs that run once across the cluster, and durable workflows that resume on another runner when one stops. Cluster →
- Atoms. Reactive values in a registry: derived atoms that update when what they read changes, effect, stream and RPC or HTTP API atoms, and state handed from a server to a client by hydration. Atoms →
- Deterministic tests. A pytest plugin with a virtual clock, so a test of a 30-second retry takes no real time. Testing →
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 25,000 tests, with a test that fails on any Effect
test title neither ported nor omitted with a reason, and about 95% of Effect's API 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. A
Duration is Effect's, exact to the nanosecond at any length or infinite, since 0.5.0. A
bare number given as a duration is milliseconds, as in Effect; write "5 seconds" or a
timedelta to say the unit. Timestamps given as numbers (testing.set_time,
clock.current_time_millis) are epoch milliseconds too.
Installation
pyfect needs Python 3.13 or later; its one dependency is typing-extensions. Install the
pyfect-dev distribution from PyPI and import pyfect (PyPI's pyfect is an unrelated
project).
uv add pyfect-dev
Optional extras: otel (OpenTelemetry), hypothesis, pydantic, msgspec, httpx (the
HTTP client backend), websockets (WebSocket clients and servers), server (the uvicorn
HTTP server), pg (the PostgreSQL driver, on psycopg), mysql (the MySQL driver, on
asyncmy), mssql (the SQL Server driver, on python-tds), redis (the Redis client, on
redis-py), crypto (cryptography and JOSE, on cryptography), eventlog (the event log's encryption, on cryptography), brotli (br response
compression on a live server, on brotlicffi), http2 (the HTTP/2 server, on hypercorn), intl (Intl-style
date formatting, on babel), regex (more ECMAScript patterns in schemas) and watch (FileSystem.watch on
the operating system's change notification, on watchfiles), for example
uv add "pyfect-dev[otel]".
pyright is the type checker pyfect is designed for. In strict mode, add
reportUnknownParameterType = false: pyright reads an unannotated generator's send type as
Unknown (pyright#10279), and effect
generators never use it. See Installation.
Learn more
- Documentation: guides for each part of the library.
- API reference: every public function and class.
- Changelog: what each release changed.
- Examples: a quickstart, batching, a FastAPI-style service, a stream pipeline and schema decoding, all checked by pyright.
- Effect's docs: the concepts carry over; pyfect uses
snake_case and
yield fromin place ofyield*.
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.
Metadata
Release files for pyfect-dev 0.5.4
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pyfect_dev-0.5.4.tar.gz | 4.7 MB | With provenance | Details for pyfect_dev-0.5.4.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pyfect_dev-0.5.4-py3-none-any.whl | Python 3 | none | any | Details for pyfect_dev-0.5.4-py3-none-any.whl |
Total release size: 10.1 MB
Release files / pyfect_dev-0.5.4.tar.gz
| Download URL | pyfect_dev-0.5.4.tar.gz |
|---|---|
| Size | 4.7 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a97aac7f2cca3be240330d8add0a5d47dc6046d645e70ce371d34c3a24649f76
|
|
BLAKE2b-256 checksum How to use checksums |
d2e8eafd2d4e8bac3749c19f8689a8a14d0c3952d526d88f60d61c72c567285d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.
Transparency logRelease files / pyfect_dev-0.5.4-py3-none-any.whl
| Download URL | pyfect_dev-0.5.4-py3-none-any.whl |
|---|---|
| Size | 5.4 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d932e4db43625d5ef8717d3c11be693ab129644ddf88be0dfc6b024c5edab9f9
|
|
BLAKE2b-256 checksum How to use checksums |
5a6a369c4963dd8dec369c883a097304627a46b9023cfd02998c1ce3a491f7a7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.
Transparency logSecurity for pyfect-dev 0.5.4
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for pyfect_dev-0.5.4.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.