Skip to main content

context-dep

Python dependency injection with minimal API using context managers. Works as DI for any Python code, including frameworks like FastAPI. Use it for configs, clients, db sessions, contexts, loggers, etc.

Instead of passing the same stuff (database, config, API clients, current user) into every function, your code can grab it when needed — it’s reused for the duration of the work, cleaned up afterward, and easy to replace with fakes in tests from one place.

pip install context-dep

Basic usage

from context_dep import dep, context


@dep(cached=True)
def get_db():
    db = Database()
    yield db
    db.close()

def my_func():
    with get_db() as db:
        ...

Overrides

@dep()
def get_mock_db():
    yield MockDatabase()

def main():
    with context({get_db: get_mock_db}):
        my_func()

Recipe: argument-scoped caching

from context_dep import dep

@dep(cached=True)
def get_session_db(env: str):
    ...

with get_session_db(env='test') as db:
    # separate cache for each environment
    ...

Recipe: stub dependency for later injection

@dep()
async def get_db():
    raise NotImplementedError

async with get_db() as db:
    ...

Cache Lifetime

When cached=True, the dependency is reused within nested calls and cleaned up once:

@dep(cached=True)
def get_db():
    db = Database()
    yield db
    db.close()

with get_db() as db:
    with get_db() as db2:  # Reuses the same instance
        assert db is db2
# Cleanup runs once when the outermost context exits

Notes

  • Works with both sync and async functions
  • Context is managed with contextvars - safe for async/await

API Reference

def dep(
    cached: bool = False,
    cache_key_func = lambda *args, **kwargs: json.dumps(
        {"args": args, "kwargs": kwargs},
        sort_keys=True,
        default=str
    ),
):
    """
    Decorator for defining dependencies.

    Args:
        cached: If True, the dependency is reused within nested calls
        cache_key_func: Function to generate cache keys from arguments.
                        Defaults to JSON serialization with sorted keys (sort_keys=True, default=str)
    """
    ...

class context:
    """Context manager to scope dependencies"""
    def __init__(self, overrides: dict[Callable, Callable]): ...

class Container:
    """
    Dependency injection container, stores the cache and overrides

    By default, `dep` and `context` use a shared global container. 
    Create separate containers for isolation (e.g., testing, multi-tenancy)
    """
    def dep(self, cached: bool = False, cache_key_func = ...): ...
    def context(self, overrides: dict[Callable, Callable]): ...

License

MIT License

Author

Mark Lidenberg marklidenberg@gmail.com

Metadata

Release files for context-dep 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for context-dep 0.1.1
File Size Uploaded
context_dep-0.1.1.tar.gz 42.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for context-dep 0.1.1
File Interpreter ABI Platform
context_dep-0.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 47.4 kB

Release files / context_dep-0.1.1.tar.gz

Download URL context_dep-0.1.1.tar.gz
Size 42.1 kB
Tags Source
SHA-256 checksum
How to use checksums
0bc6da9c83f4d94195492206926ab4e3d4c7d250fb1b87dd71ff50f54cd092a8
BLAKE2b-256 checksum
How to use checksums
7dbd2088ecb3b20451d95c98b2aeb27e9d4b9928319e81edf2a845c5ab4c0aba
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.7.2

Release files / context_dep-0.1.1-py3-none-any.whl

Download URL context_dep-0.1.1-py3-none-any.whl
Size 5.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
889147eedd1cc60ab0702752a51b5a8a6b2a53ee99b47dd9ad1a480aab96aba1
BLAKE2b-256 checksum
How to use checksums
7e10b3cb9e7c40839e90644145fbd930a96fda61e0959b2df41a171f5b9a8792
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.7.2

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release 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