Skip to main content

No project description provided

Project description

Ninject 🥷

PyPI - Version PyPI - Python Version License: MIT

Ninject uses modern Python features to provide a simple and performant dependency injection framework.

Installation

pip install ninject

Basic Usage

First declare a Dependency and inject it into a dependent function.

from ninject import Dependency, inject

Message = Dependency("Message", str)


@inject
def print_message(*, message: Message = inject.ed):
    print(message)

Next, define a Context with a function that provides the Dependency.

from ninject import Context

context = Context()


@context.provides
def provide_message() -> Message:
    return Message("Hello, World!")

Finally, establish the context and call the function with the inject.ed dependency:

with context:
    print_message()

The output will be:

Hello, World!

Types of Providers

A provider is one of the following

  • A function that returns a value
  • A generator that yields a single value
  • A context manager class that yields a value
  • An async function that returns a value
  • An async generator that yields a single value
  • An async context manager class that yields a value
from ninject import Dependency, Context

Message = Dependency("Message", str)

context = Context()

# --- Sync Providers -------------------------------------


@context.provides
def sync_function() -> Message:
    return Message("Hello, World!")


@context.provides
def sync_generator() -> Message:
    try:
        yield Message("Hello, World!")
    finally:
        pass


@context.provides
class SyncContextManager:
    def __enter__(self) -> Message:
        return Message("Hello, World!")

    def __exit__(self, *args) -> None:
        pass


# --- Async Providers ------------------------------------


@context.provides
async def async_function() -> Message:
    return Message("Hello, World!")


@context.provides
async def async_generator() -> Message:
    try:
        yield Message("Hello, World!")
    finally:
        pass


@context.provides
class AsyncContextManager:
    async def __aenter__(self) -> Message:
        return Message("Hello, World!")

    async def __aexit__(self, *args) -> None:
        pass

Providers with Dependencies

Providers can have their own dependencies:

from ninject import Context, Dependency, inject

Greeting = Dependency("Greeting", str)
Recipient = Dependency("Recipient", str)
Message = Dependency("Message", str)


@inject
def print_message(*, message: Message = inject.ed):
    print(message)


context = Context()


@context.provides
def provide_greeting() -> Greeting:
    return Greeting("Hello")


@context.provides
def provide_recipient() -> Greeting:
    return Greeting("World")


@context.provides
def provide_message(
    *, greeting: Greeting = inject.ed, recipient: Recipient = inject.ed
) -> Message:
    return Message(f"{greeting}, {recipient}!")


if __name__ == "__main__":
    with context:
        print_message()

The output will be:

Hello, World!

Providing Multiple Dependencies

A single provider can supply multiple dependencies:

from ninject import Context, Dependency, inject

Greeting = Dependency("Greeting", str)
Recipient = Dependency("Recipient", str)
MessageContent = tuple[Greeting, Recipient]


@inject
def print_message(*, greeting: Greeting = inject.ed, recipient: Recipient = inject.ed):
    print(f"{greeting}, {recipient}!")


context = Context()


@context.provides
def provide_message_content() -> MessageContent:
    return "Hello", "World"


if __name__ == "__main__":
    with context:
        print_message()

You may also depend on MessageContent directly:

from ninject import Context, Dependency, inject

Greeting = Dependency("Greeting", str)
Recipient = Dependency("Recipient", str)
MessageContent = tuple[Greeting, Recipient]


@inject
def print_message(*, message_content: MessageContent = inject.ed):  # TypeError!
    greeting = message_content["greeting"]
    recipient = message_content["recipient"]
    print(f"{greeting}, {recipient}!")


context = Context()


@context.provides(MessageContent)
def provide_message_content() -> dict:
    return {"greeting": "Hello", "recipient": "World"}


if __name__ == "__main__":
    with context:
        print_message()

Providing Dependencies Concurrently

Ninject does not execute async providers concurrently since doing so can add a substantial amount of overhead to async function calls if it's unnecessary. If you want to satisfy dependencies concurrently you can leverage the ability to provide multiple dependencies at once. With that in mind, you can use asyncio.gather to run several async functions concurrently before returning the dependencies:

import asyncio
from ninject import Context, Dependency, inject

Greeting = Dependency("Greeting", str)
Recipient = Dependency("Recipient", str)


@dependencies
class MessageContent(TypedDict):
    greeting: Greeting
    recipient: Recipient


@inject
async def print_message(
    *, greeting: Greeting = inject.ed, recipient: Recipient = inject.ed
):
    print(f"{greeting}, {recipient}!")


context = Context()


async def get_message() -> str:
    return "Hello"


async def get_recipient() -> str:
    return "World"


@context.provides(MessageContent)
async def provide_message_content() -> dict:
    greeting, recipient = await asyncio.gather(get_message(), get_recipient())
    return {"greeting": greeting, "recipient": recipient}


if __name__ == "__main__":
    with context:
        asyncio.run(print_message())

Mixing Async and Sync Providers

To mix async and sync providers, the highest order dependent function must be async. So, in the example below, that highest order dependent async function is print_message. The fact that print_message is async is what allows the sync provide_message function to depend on the async provide_recipient function:

import asyncio
from ninject import Context, Dependency, inject

Greeting = Dependency("Greeting", str)
Recipient = Dependency("Recipient", str)

context = Context()


@context.provides(Recipient)
async def provide_recipient() -> str:
    return "World"


@context.provides(Message)
def provide_message(*, recipient: Recipient = inject.ed) -> str:
    return f"Hello, {recipient}!"


@inject
async def print_message(*, message: Message = inject.ed):
    print(message)


if __name__ == "__main__":
    with context:
        asyncio.run(print_message())

If print_message were sync, then the following error would be raised:

RuntimeError: Cannot use an async context manager in a sync context

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

ninject-0.0.2.tar.gz (14.0 kB view details)

Uploaded Source

Built Distribution

ninject-0.0.2-py3-none-any.whl (9.7 kB view details)

Uploaded Python 3

File details

Details for the file ninject-0.0.2.tar.gz.

File metadata

  • Download URL: ninject-0.0.2.tar.gz
  • Upload date:
  • Size: 14.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-httpx/0.27.0

File hashes

Hashes for ninject-0.0.2.tar.gz
Algorithm Hash digest
SHA256 6ed6eacc23b99da0ccd187e76c12de7fbf2c1e177d642a32ac7fa4353ecf4d14
MD5 68e9178686f90a00d02322cf9347e24b
BLAKE2b-256 7f3dd7f4711ea730b4e20831520b71d4c3b108c3d4474817c68c9468a40e3078

See more details on using hashes here.

File details

Details for the file ninject-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: ninject-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 9.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-httpx/0.27.0

File hashes

Hashes for ninject-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 b341d84efef7df04579b298f9d23be47e5c809bc92d199156d773e1debe740c1
MD5 b03a5072a1b1ba92edee2dd1eb81d08e
BLAKE2b-256 49afb6803377e69c2ce122b164ecef50a167ddf3e48ceb17a207519af8270c01

See more details on using hashes here.

Supported by

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