Skip to main content

fastapi_di

Depends で依存を明示する汎用 DI。解決戦略(リゾルバ)を差し替えられる。

名前のとおり FastAPI の DI に似せている。Depends / Dependant / solve_dependencies の設計を踏襲しつつ、HTTP 依存(Request、query/path/body、 pydantic 検証)を全て剥がした。FastAPI には依存せず(依存パッケージなし)、 Web に限らずパイプライン処理・バッチ・CLI・ライブラリ内部の配線に使える。

  • 依存は明示 Depends のみ。型アノテーションによる自動ワイヤリングはしない。 書いていないものは注入されない。
  • 解析と実行が分かれている。シグネチャを辿るだけで依存グラフが得られる(実行しない)。
  • 参照の意味を差し替えられるDepends("name")"name" が何を指すかは リゾルバが決める。既定は完全一致だが、チェーンや凍結表に差し替えられる。

要件: Python >= 3.14 / 依存パッケージなし。

インストール

uv add fastapi_di

使う

import asyncio
from typing import Annotated

from fastapi_di import Depends, Injector


def get_settings() -> dict:
    return {"dsn": "postgres://localhost"}


def get_dsn(settings: Annotated[dict, Depends(get_settings)]) -> str:
    return settings["dsn"]


class Database:
    def __init__(self, dsn: str = Depends(get_dsn)) -> None:
        self.dsn = dsn


async def main() -> None:
    injector = Injector()
    async with injector.scope() as scope:            # スコープ = 依存の生存期間
        db = await scope.inject(Database)    # Database -> get_dsn -> get_settings
        print(db.dsn)


asyncio.run(main())

クラス内の派生値(depend_property)

depend_property は getter の引数を同じクラスのメンバから解決するプロパティ。 Injector とは無縁の同期ディスクリプタで、Depends の構文だけを共有する。 既定はキャッシュしない(毎回再計算)。cache="auto" にすると依存から戦略が 伝搬し(cached_property だけに依存すれば自分もキャッシュ、property が混ざれば 毎回再計算)、cache=True で強制キャッシュする。

from functools import cached_property

from fastapi_di import Depends, depend_property


class Service:
    @cached_property
    def user(self) -> dict:
        return {"name": "alice", "deleted_at": None}

    @depend_property(cache="auto")
    def is_active_user(self, user=Depends(user)) -> bool:
        return user["deleted_at"] is None


print(Service().is_active_user)  # True(user が cached かつ cache="auto" なのでキャッシュされる)

詳細は 使う を参照。

ビジョン

狙いは依存性の解決を標準化すること。三段階で考えている。

  1. 小回りの利く小さな DI — 数十行のスクリプトから使える。フレームワークを 持ち込まず、Depends を書くだけ。今ここ。
  2. パイプライン処理などへの展開 — 依存グラフは DAG そのもの。同じ宣言から 実行順序・並列性・キャッシュ境界を導ける。DI とワークフローを別物にしない。
  3. 依存関係の定義フォーマット — OpenAPI が HTTP インターフェースに対して 果たした役割を、依存関係に対して果たすもの。何が何に依存しているかを 機械可読な形で宣言・可視化・検証でき、言語や実装をまたいで共有できる形式。

graph.to_json()bindings.json は、その 3 番目に向けた最初の一歩。 前者が「どう繋がっているか」、後者が「なぜそう繋がったか」を外に出す。

ドキュメント

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_di-0.1.1.tar.gz (74.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_di-0.1.1-py3-none-any.whl (45.9 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_di-0.1.1.tar.gz.

File metadata

  • Download URL: fastapi_di-0.1.1.tar.gz
  • Upload date:
  • Size: 74.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for fastapi_di-0.1.1.tar.gz
Algorithm Hash digest
SHA256 caa5db2864638b01e069f1f3124d6680487f673d3bf4f792514c00355555d22b
MD5 660cbf6e04a1e1abd199830b486c76a8
BLAKE2b-256 0ace2e0d875d564bd63473b8789b1d40c8c67c2957f3ccf4d488f81692fae3bf

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_di-0.1.1.tar.gz:

Publisher: release.yml on sasano8/fastapi_di

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fastapi_di-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: fastapi_di-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 45.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for fastapi_di-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 028025ba61b44306fc7eca2cfa0e8e22eb72e3caf109dc483a222b9285d01656
MD5 293c95c9f6eff7064dbad53585806376
BLAKE2b-256 b965aec6187cc92c4030253c7e61476301fcf94e4e2f5efbe3db82a7eb7054af

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_di-0.1.1-py3-none-any.whl:

Publisher: release.yml on sasano8/fastapi_di

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

0.1.2

2 files

This release

0.1.1 This release

2 files

0.1.0

2 files

0.0.1

2 files

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