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())))
)

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

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

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 →
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 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.6.18

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.6.18
File Size Uploaded Provenance Actions
pyfect_dev-0.6.18.tar.gz 6.5 MB With provenance Details for pyfect_dev-0.6.18.tar.gz

Built distribution (wheel)

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

Total release size: 13.7 MB

Release files / pyfect_dev-0.6.18.tar.gz

Download URL pyfect_dev-0.6.18.tar.gz
Size 6.5 MB
Tags Source
SHA-256 checksum
How to use checksums
0de8b066f35c7d8a7b209f0c64f989acd7a82e2de85c34cc31997af007d2fc0f
BLAKE2b-256 checksum
How to use checksums
97729e1557ed6abcbbd3593f0bebce77f8dc149e272dfe5b28aa7b1f4056d7dc
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 log

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

Download URL pyfect_dev-0.6.18-py3-none-any.whl
Size 7.2 MB
Tags Python 3
SHA-256 checksum
How to use checksums
e36eee6b4ca33a93b27ecc1f19c5e12c9b806659a2f1abf89cad058ef3d933ab
BLAKE2b-256 checksum
How to use checksums
b2f2278b84324734f51e19caf367b234ddb495b944d22e7442521534edfcd07e
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 log

Security for pyfect-dev 0.6.18

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