Python dependency injection library
Project description
Python Dependency Injection Library
Install
pip3 install pythondi
Usage
- Add injection policy
from pythondi import Provider, configure, configure_after_clear
# Init provider
provider = Provider()
# Bind `Impl` class to `Interface` class
provider.bind(Repo, SQLRepo)
# Inject with configure
configure(provider=provider)
# Or if you want to fresh inject, use `configure_after_clear`
configure_after_clear(provider=provider)
- Import inject
from pythondi 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 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.
Full Example
import abc
from pythondi import Provider, configure, configure_after_clear, inject
class Repo:
"""Interface class"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def get(self):
pass
class SQLRepo(Repo):
"""Impl class"""
def __init__(self):
pass
def get(self):
print('SQLRepo')
class Usecase:
@inject()
def __init__(self, repo: Repo):
self.repo = repo
if __name__ == '__main__':
# Init provider
provider = Provider()
# Bind `Impl` class to `Interface` class
provider.bind(Repo, SQLRepo)
# Inject with configure
configure(provider=provider)
# Or if you want to fresh inject, use `configure_after_clear`
configure_after_clear(provider=provider)
# Init class without arguments
u = Usecase()
print(u.__dict__)
Project details
Release history Release notifications | RSS feed
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.2.tar.gz
(2.8 kB
view hashes)