Skip to main content

A simple dependency injector for Python

Project description

dinjectorr

A simple dependency injector for Python.

Installation

pip install dinjectorr

Usage

Example 1:

from dinjectorr import inject

class A:
    def print_hello(self):
        print("Hello from A")

class B:
    @inject
    def __init__(self, a: A):
        self._a = a

    def print_hello(self):
        self._a.print_hello()

b = B()
b.print_hello()
# Output:
# Hello from A

Example 2:

from dinjectorr import Injector

class Client:
    def __init__(self, api_key: str):
        self._api_key = api_key

    def print_api_key(self):
        print(self._api_key)

Injector.register(Client, api_key="some_api_key")
client = Injector.get_instance(Client)
client.print_api_key()
# Output:
# some_api_key

Example 3:

from dinjectorr import inject, Injector

class Client:
    def __init__(self, api_key: str):
        self._api_key = api_key

    def print_api_key(self):
        print(self._api_key)

class CustomClient(Client):
    @inject
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

Injector.register(CustomClient, api_key="some_api_key")
custom_client = CustomClient()
custom_client.print_api_key()
# Output:
# some_api_key

Example 4:

from dinjectorr import inject, Injector

class Client:
    def __init__(self, api_key: str):
        self._api_key = api_key

    def print_api_key(self):
        print(self._api_key)

class CustomClient(Client):
    @inject
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

Injector.register(CustomClient, api_key="some_api_key")
custom_client = CustomClient(api_key="another_api_key")
custom_client.print_api_key()
# Output:
# another_api_key

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

dinjectorr-0.1.8.tar.gz (2.9 kB view hashes)

Uploaded Source

Built Distribution

dinjectorr-0.1.8-py3-none-any.whl (3.9 kB view hashes)

Uploaded Python 3

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