Dependency injection for python
Project description
By: CenturyBoys
Witch-doctor
A simple dependency injection for python
Register
Witch Doctor provides a method to register interfaces and his implementation. The interface and implementation inheritance will be check and will raise a TypeError if was some error.
class WitchDoctor:
@classmethod
def register(cls, interface: Type[ABC], class_ref: Any):
"""
WitchDoctor.register will check inherit of the interface and class_ref.
Will raise a TypeError on validation error\n
:param interface: Interface that inherits from ABC
:param class_ref: A implementation of the interface
"""
pass
Injection
Witch Doctor must be used as decorator. The function signature will ber check and if some values was not provide Witch Doctor will search on the registered interfaces to inject the dependencies.
class WitchDoctor:
@classmethod
def injection(cls, function: Callable):
"""
WitchDoctor.injection is a function decorator that will match the
function params signature and inject the dependencies.
Will raise AttributeError is some args was pass throw\n
:type function: Callable
"""
pass
Usage example
from abc import ABC, abstractmethod
from witch_doctor import WitchDoctor
class IStubFromABCClass(ABC):
@abstractmethod
def sum(self, a: int, b: int):
pass
class StubFromABCClass(IStubFromABCClass):
def sum(self, a: int, b: int):
return a + b
WitchDoctor.register(IStubFromABCClass, StubFromABCClass)
@WitchDoctor.injection
def func_t(a: int, b: int, c: IStubFromABCClass):
return c.sum(a, b), c
result_a1, reference_a1 = func_t(a=1, b=2)
result_a2, reference_a2 = func_t(a=2, b=2)
assert result_a1 == 3
assert result_a2 == 4
assert reference_a1 == reference_a2
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
witch_doctor-0.1.1.tar.gz
(6.6 kB
view hashes)
Built Distribution
Close
Hashes for witch_doctor-0.1.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | fbfd8e1bc0e2204b7820b3e65ba923e5d9eaeecf6f5ef89174d44662fda05c01 |
|
MD5 | e4610a5d62d3ea413966d69e375ae682 |
|
BLAKE2b-256 | 4b49d6341386ce08877a9b5de238f2e6e880651e798394d7846e1cb2fa1f6fd1 |