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())))
)
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.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
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 anExceptionGroupforexcept*. Errors → - Services and layers: dependency injection pyright checks, with memoized layers that release in order. Services →
- Its own fiber runtime:
run_blockingwith no event loop, or on asyncio;blockingmoves calls to a thread. Effects → - Structured concurrency: children end with their parent,
allandfor_eachtake a limit, races clean up. Concurrency → - Resources: scopes,
acquire_release, pools,RcRefandRcMaprelease exactly once, even on interruption, andwith fx.managed(...)holds one in plain Python code. Resources → - Parallel work:
fx.on_threadruns an effect on a thread of its own, in parallel on free-threaded Python, andinterpreter_poolruns pure functions in subinterpreters on several cores. Parallel effects → · Subinterpreters → - Retries and schedules: exponential, jittered, cron and composed schedules for
retryandrepeat. 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
Annotatedincluded), compiled decoders, JSON Schema, Hypothesis, pydantic and msgspec. Schema → - Config: typed settings from the environment,
.envfiles 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
LanguageModelwith 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 →
Storage and distributed systems: SQL, models, persistence, rate limiting, workers, workflows, event log, cluster
- 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 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.6.17
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.6.17.tar.gz | 6.5 MB | With provenance | Details for pyfect_dev-0.6.17.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pyfect_dev-0.6.17-py3-none-any.whl | Python 3 | none | any | Details for pyfect_dev-0.6.17-py3-none-any.whl |
Total release size: 13.6 MB
Release files / pyfect_dev-0.6.17.tar.gz
| Download URL | pyfect_dev-0.6.17.tar.gz |
|---|---|
| Size | 6.5 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d22461ebfe9132c55b17557c929f0d27511aa196c2c1451175f99c060d1c1703
|
|
BLAKE2b-256 checksum How to use checksums |
b7bd265d7ce83e7f6c66871ba223556347ea76275929a2e344928517537cb395
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","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 21, 2026.
Transparency logRelease files / pyfect_dev-0.6.17-py3-none-any.whl
| Download URL | pyfect_dev-0.6.17-py3-none-any.whl |
|---|---|
| Size | 7.2 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4f8a9e77878162dc3296fba35acbb6ba920f2bbf3b69a62235f3e9b552cf6dea
|
|
BLAKE2b-256 checksum How to use checksums |
a4158128a726625965057ad3d452730338f6e3dff04d9e4a46d1f62a46b14535
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","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 21, 2026.
Transparency logSecurity for pyfect-dev 0.6.17
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.6.17.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 21, 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.