Skip to main content

A lightweight, intuitive dependency injection library for Python that makes testing and dependency management a breeze.

Project description

DIWrappers

A lightweight, intuitive dependency injection library for Python that makes testing and dependency management a breeze.

Features

  • Simple decorator-based dependency injection
  • Built-in support for singleton and transient dependencies
  • Seamless integration with popular frameworks like FastAPI
  • Powerful testing utilities with context managers
  • Type hint friendly with full Pydantic support

Installation

pip install diwrappers

Quick Start

Here's a simple example showing how to inject a configuration dependency:

from diwrappers import dependency
from pydantic import SecretStr
import os

@dependency
def api_token() -> SecretStr:
    return SecretStr(os.environ["API_TOKEN"])

@api_token.inject
def send_request(api_token: SecretStr):
    return f"Sending request with token: {api_token.get_secret_value()}"

Core Concepts

Dependency Types

Transient Dependencies

Transient dependencies are created each time they're requested. Perfect for generating random values or creating new instances:

from diwrappers import dependency
import random

@dependency
def random_number():
    return random.randint(1, 10)

@random_number.inject
def play_game(random_number: int) -> str:
    return "win" if random_number > 5 else "lose"

Singleton Dependencies

Singleton dependencies are created once and reused. Ideal for database connections, configuration, or API clients:

from functools import cache
from pydantic import HttpUrl

@dependency
@cache  # Makes this a singleton
def api_base_url():
    return HttpUrl("https://api.example.com")

Chaining Dependencies

Dependencies can be chained together to build complex injection hierarchies:

@dependency
def database():
    return Database("connection_string")

@dependency
@database.inject
def user_repository(database: Database):
    return UserRepository(database)

@user_repository.inject
def get_user(user_repository: UserRepository, user_id: int):
    return user_repository.get_user(user_id)

Framework Integration

DIWrappers works seamlessly with popular frameworks like FastAPI:

from fastapi import FastAPI
from diwrappers import dependency

app = FastAPI()

@dependency
def db_connection():
    return "database_connection"

@app.get("/users/{user_id}")
@db_connection.inject
def get_user(user_id: int, db_connection: str):
    return {"user_id": user_id, "connection": db_connection}

Testing

DIWrappers provides powerful utilities for testing injected dependencies:

Using Context Managers

@dependency
def api_key():
    return "production_key"

@api_key.inject
def make_request(api_key: str):
    return f"Request with {api_key}"

def test_make_request():
    with api_key.fake_value("test_key"):
        assert make_request() == "Request with test_key"

Dynamic Fake Data

Create dynamic fake data for more complex testing scenarios:

@dependency
def user_id():
    return get_current_user_id()

@user_id.faker
def fake_user_id():
    return random.randint(1000, 9999)

def test_with_random_users():
    with fake_user_id():
        result = get_user_data()
        assert 1000 <= result.user_id <= 9999

Multiple Fakes

Chain multiple fake dependencies in a single test:

def test_complex_scenario():
    with (
        api_key.fake_value("test_key"),
        database.fake_value(MockDatabase()),
        user_id.fake_value(12345)
    ):
        result = perform_operation()
        assert result.success

Coming Soon

  • Contextual dependency injection (request-scoped, session-scoped)
  • Async support
  • Container lifecycle management
  • Enhanced framework integrations

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Download files

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

Source Distribution

diwrappers-0.2.7.tar.gz (6.5 kB view details)

Uploaded Source

Built Distribution

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

diwrappers-0.2.7-py3-none-any.whl (7.2 kB view details)

Uploaded Python 3

File details

Details for the file diwrappers-0.2.7.tar.gz.

File metadata

  • Download URL: diwrappers-0.2.7.tar.gz
  • Upload date:
  • Size: 6.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.0.1 CPython/3.12.8 Linux/6.8.0-1017-azure

File hashes

Hashes for diwrappers-0.2.7.tar.gz
Algorithm Hash digest
SHA256 03e3639034e02da424c65d54d275d1d9f6eabdf072b60f4a272253d0d1a20c6c
MD5 5847fb55de0e53a3d11e58dd189147c5
BLAKE2b-256 964b14330bf6d33bb3b68b7c58ba21a22672d7631e9a5d7d1ca223b92ee66885

See more details on using hashes here.

File details

Details for the file diwrappers-0.2.7-py3-none-any.whl.

File metadata

  • Download URL: diwrappers-0.2.7-py3-none-any.whl
  • Upload date:
  • Size: 7.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.0.1 CPython/3.12.8 Linux/6.8.0-1017-azure

File hashes

Hashes for diwrappers-0.2.7-py3-none-any.whl
Algorithm Hash digest
SHA256 9c28556320ac0a400a56f8687a718ecac2e0a3b0de938b4c5669eabe4451d6ab
MD5 762b7871563a38696ca18c76fc3c59eb
BLAKE2b-256 3ef5c1ead573ef1f02ff097f85b5b8f70cf2944688f56a4d757e3429b685c796

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page