FastDepends

3.0.8 · active · verified Sat Apr 11

FastDepends is a lightweight Python library providing a dependency injection system, extracted and refined from FastAPI's core logic. It allows developers to use FastAPI-like dependency resolution and type casting in any Python project, whether synchronous or asynchronous, without the HTTP-specific components. Currently at version 3.0.8, the library maintains an active development pace with frequent updates and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic synchronous and asynchronous dependency injection using the `@inject` decorator and `Depends` for declaring dependencies. The `get_user_id` dependency is resolved and injected into `process_data`, while `async_get_greeting` is resolved into `greet_user`.

from fast_depends import inject, Depends

def get_user_id() -> int:
    return 42

@inject
def process_data(data: str, user_id: int = Depends(get_user_id)) -> str:
    return f"Processing '{data}' for user {user_id}"

result = process_data("hello world")
print(result)

# Async example (requires an event loop)
import asyncio

async def async_get_greeting() -> str:
    await asyncio.sleep(0.1)
    return "Hello"

@inject
async def greet_user(name: str, greeting: str = Depends(async_get_greeting)) -> str:
    return f"{greeting}, {name}!"

async def main_async():
    async_result = await greet_user("Alice")
    print(async_result)

# To run the async example in a synchronous environment:
# asyncio.run(main_async())

view raw JSON →