Skip to main content

Python lightweight dependency injection framework

Project description

pydilite

license


pydilite is a lightweight dependency injection library for python supporting both sync and async functions.

It is strongly based on ![pythondi]

Installation

pip3 install pydilite

Usage

Bind classes to the provider

from pydilite import Provider

provider = Provider()
provider.bind(Repo, SQLRepo)
provider.bind(Usecase, CreateUsecase)

After binding, configure the provider to the container

from pydilite import configure, configure_after_clear


# Inject with configure
configure(provider=provider)

# Or if you want to fresh inject, use `configure_after_clear`
configure_after_clear(provider=provider)

Define injection

Define the kind of injection you want to use on your clases.

Import inject

from pydilite import inject

Add type annotations that you want to inject dependencies

class Usecase:
    def __init__(self, repo: Repo):
        self.repo = repo

Add decorator

class Usecase:
    @inject()
    def __init__(self, repo: Repo):
        self.repo = repo

Initialize the destination class with no arguments as they are being injected automatically.

usecase = Usecase()

Or, you can also inject manually through decorator arguments

class Usecase:
    @inject(repo=SQLRepo)
    def __init__(self, repo):
        self.repo = repo

In this case, do not have to configure providers and type annotation.

Lazy initializing

Using lazy initilization the injected classes will be built when used. It can be used to preinitialize a class with parameters in the constructor.

from pydilite import Provider

provider = Provider()
provider.bind(Repo, SQLRepo, lazy=True)

You can use lazy initializing through lazy option. (default False)

For singleton, use lazy=False.

class Usecase:
    @inject(repo=SQLRepo)
    def __init__(self, repo):
        self.repo = repo

By default, manual injection is lazy. If you want a singleton, instantiate it like repo=SQLRepo().

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

pydilite-0.1.0.tar.gz (7.5 kB view hashes)

Uploaded Source

Built Distribution

pydilite-0.1.0-py3-none-any.whl (8.8 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