Skip to main content

Python dependency injection library

Project description

Python Dependency Injection Library

Usage

  1. Add injection policy
from pythondi import Provider, configure


class DI:
    def __init__(self):
        self.provider = Provider()

    def bind_to_provider(self) -> None:
        # Inject `Impl` class to `Interface` class
        self.provider.bind(Repo, SQLRepo)

    def bind_and_configure(self) -> None:
        # Binding provider
        self.bind_to_provider()

        # Configure injector
        configure(provider=self.provider)

        # Configure injector after clear provider
        configure_after_clear(provider=self.provider)


if __name__ == '__main__':
    di = DI()
    di.bind_and_configure()
  1. Import inject
from pythondi import inject
  1. Add type annotations that you want to inject dependencies
class Usecase:
    def __init__(self, repo: Repo):
        self.repo = repo
  1. Add decorator
class Usecase:
    @inject()
    def __init__(self, repo: Repo):
        self.repo = repo
  1. Initialize class with no arguments
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.

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

PythonDI-1.0.0.tar.gz (2.1 kB view hashes)

Uploaded Source

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