Skip to main content

pyfect logo

pyfect

Effect for Python. Errors, dependencies and concurrency checked by pyright.

PyPI Docs Python 3.13+ pyright strict MIT license

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

An @fx.fn generator builds Effect[A, E, R]; catch_tag removes an error, provide(layer) removes a service, and run_blocking runs the Effect[A, Never, Never] to an Exit.

  1. 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.
  2. Narrow. Each handler removes exactly the error it handles, and each layer removes exactly the services it builds. The type shrinks as you go.
  3. 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_tag handles 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. blocking moves blocking calls to a thread. Effects →
  • Structured concurrency. Children end with their parent; all and for_each take a concurrency limit; races wait for losers to clean up. Concurrency →
  • Resources. Scopes, acquire_release, pools, RcRef and RcMap release exactly once, even on interruption. Resources →
  • 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, 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 →
  • Config. Typed settings from the environment, .env files 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 LanguageModel for 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 v4, does what Effect does wherever Python can express it, and runs Effect's own test cases as its spec: over 22,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 bare number as a Duration is milliseconds, as in Effect, since 0.2.0 (0.1.0 read it as seconds); 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), eventlog (the event log's encryption, on cryptography), brotli (br response compression on a live server), http2 (the HTTP/2 server, on hypercorn), intl (Intl-style date formatting, on babel) and regex (more ECMAScript patterns in schemas), 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 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.

Metadata

Release files for pyfect-dev 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pyfect-dev 0.2.0
File Size Uploaded Provenance Actions
pyfect_dev-0.2.0.tar.gz 4.3 MB With provenance Details for pyfect_dev-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pyfect-dev 0.2.0
File Interpreter ABI Platform Actions
pyfect_dev-0.2.0-py3-none-any.whl Python 3 none any Details for pyfect_dev-0.2.0-py3-none-any.whl

Total release size: 9.3 MB

Release files / pyfect_dev-0.2.0.tar.gz

Download URL pyfect_dev-0.2.0.tar.gz
Size 4.3 MB
Tags Source
SHA-256 checksum
How to use checksums
b43fec28ae1ff28b6507c30928e0384ffe9868ed18ebc62e28b15a3eb32f7fce
BLAKE2b-256 checksum
How to use checksums
a2b008036301e7ab50dd9aaaab8bb718462c77b82416bd7e06526b8e72408149
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 9, 2026.

Transparency log

Release files / pyfect_dev-0.2.0-py3-none-any.whl

Download URL pyfect_dev-0.2.0-py3-none-any.whl
Size 4.9 MB
Tags Python 3
SHA-256 checksum
How to use checksums
b5a1bf8600aafb9aa599456bbdb586b224a9d7b3aad07e59bbd2172af593c0f0
BLAKE2b-256 checksum
How to use checksums
fc3cc4042a113c870f6b533edd2005f13c014f12279c4b8e7d7a2142cd58edae
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 9, 2026.

Transparency log

Security for pyfect-dev 0.2.0

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.

Select from 2 files

Attestation for pyfect_dev-0.2.0.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 9, 2026.

Transparency log

A 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.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page