Python dependency injection library
Project description
Python Dependency Injection Library
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.1.tar.gz
(2.8 kB
view details)
File details
Details for the file PythonDI-1.0.1.tar.gz.
File metadata
- Download URL: PythonDI-1.0.1.tar.gz
- Upload date:
- Size: 2.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/2.0.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.6.0 requests-toolbelt/0.9.1 tqdm/4.38.0 CPython/3.7.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a10de91b2318c5d74a2fb5bf4fcea2165cb84044c4edff2917fa45e8e82fdc3f
|
|
| MD5 |
2783f7f67a64c0c18b8280bcf2b2f5f6
|
|
| BLAKE2b-256 |
701cdf1997f47f338e706b0489e9341f59dc3c8ad47185aa4576cfaaaa8621a9
|