Skip to main content

Dependency injection for python

Project description

drawing By: CenturyBoys


A simple dependency injection for python


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:
    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


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:
    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

Usage example

from abc import ABC, abstractmethod

from witch_doctor import WitchDoctor

class IStubFromABCClass(ABC):
    def sum(self, a: int, b: int):
class StubFromABCClass(IStubFromABCClass):
    def sum(self, a: int, b: int):
        return a + b
WitchDoctor.register(IStubFromABCClass, StubFromABCClass)

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.2.tar.gz (6.6 kB view hashes)

Uploaded Source

Built Distribution

witch_doctor-0.1.2-py3-none-any.whl (6.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