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, type-safe dependency injection library for Python that supports synchronous, asynchronous, and contextual dependencies.

Features

  • Type-safe dependency injection with Python type hints
  • Three injection patterns:
    • Regular dependencies (@dependency)
    • Async dependencies (@async_dependency)
    • Contextual dependencies (@contextual_dependency)
  • Testing utilities for mocking dependencies
  • Support for singleton dependencies via @cache
  • Minimal boilerplate and intuitive API

Installation

pip install diwrappers

Usage

Basic Dependency Injection

from diwrappers import dependency

@dependency
def api_token() -> str:
    return "your-api-token"

@api_token.inject
def make_request(api_token: str, endpoint: str):
    return f"Calling {endpoint} with token {api_token}"

# The api_token will be automatically injected
result = make_request("/users")

Async Dependencies

For dependencies that require asynchronous initialization:

from diwrappers import async_dependency

@async_dependency
async def database():
    connection = await establish_db_connection()
    return connection

@database.inject
async def get_user(db, user_id: int):
    return await db.query(f"SELECT * FROM users WHERE id = {user_id}")

# Use with async/await
user = await get_user(123)

Contextual Dependencies

For dependencies that need proper resource management:

from diwrappers import contextual_dependency
import contextlib

@contextual_dependency
@contextlib.contextmanager
def db_transaction():
    transaction = start_transaction()
    try:
        yield transaction
        transaction.commit()
    except:
        transaction.rollback()
        raise

@db_transaction.inject
def update_user(transaction, user_id: int, data: dict):
    transaction.execute("UPDATE users SET ...", data)

# Must be wrapped in ensure() to properly manage the context
@db_transaction.ensure
def main():
    update_user(123, {"name": "New Name"})

Testing

The library provides utilities for mocking dependencies in tests:

Using fake_value

@dependency
def current_time() -> float:
    return time.time()

# In tests
with current_time.fake_value(1234567890.0):
    assert get_timestamp() == 1234567890.0

Using faker

@dependency
def random_id() -> str:
    return str(uuid.uuid4())

@random_id.faker
def fixed_id():
    return "test-id-123"

# In tests
with fixed_id():
    assert create_resource().id == "test-id-123"

Singleton Dependencies

To create singleton dependencies that are cached for the lifetime of the program:

from functools import cache

@dependency
@cache
def config():
    return load_config_from_file()

Type Safety

The library leverages Python's type hints to ensure type safety:

@dependency
def logger() -> Logger:
    return Logger()

@logger.inject
def process_data(logger: Logger, data: dict) -> None:
    logger.info(f"Processing {data}")  # Type-checked by your IDE/mypy

Best Practices

  1. Keep dependency constructors simple and focused
  2. Use @cache for expensive-to-create dependencies that can be reused
  3. Prefer contextual dependencies for resources that need cleanup
  4. Always wrap contextual dependency usage with ensure()
  5. Use async dependencies for I/O-bound operations

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.4.3.tar.gz (8.6 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.4.3-py3-none-any.whl (10.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: diwrappers-0.4.3.tar.gz
  • Upload date:
  • Size: 8.6 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.4.3.tar.gz
Algorithm Hash digest
SHA256 4e6d1ac532017275793a201ca1631b7eb8ef110dc926d29dc71f7e0586eab538
MD5 e90e21a614747eb85d4c88902d4f4650
BLAKE2b-256 f45b59a424b1bad3904a4d4c2d9719a6de3f2187015c73d59da800168a4fe092

See more details on using hashes here.

File details

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

File metadata

  • Download URL: diwrappers-0.4.3-py3-none-any.whl
  • Upload date:
  • Size: 10.6 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.4.3-py3-none-any.whl
Algorithm Hash digest
SHA256 7a0b141e898d1aeb434e8a1040a32d4a59c10e2a1356dfad0591f4a05f260e6f
MD5 59398a3be6e7c2e98cfd20b7a4c1b6f8
BLAKE2b-256 9c027552a37c0101ff808ccf5b8965cd6b63796554838803b6222d15621129e1

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