跳转到主要内容

类型提示的依赖注入

项目描述

Wint - 基于类型提示的依赖注入。

Build Status Coverage Status

简介

Wint是一个轻量级库,通过类型提示实现依赖注入。

安装

只需使用pip

$ pip install wint

工作原理

有大量的DI方法,这个库仅实现了属性注入。

当应用了autowired装饰器时,类将检查所有注解属性。如果属性没有值,则将其替换为DependencyDescriptor

当在实例化类实例上访问属性时解决依赖关系。

这种行为允许以懒加载的方式解决依赖关系,但缺点是实例会收到之前不存在的描述符属性。

示例

from wint import autowired, ContainerProvider


class Printer:
    """Abstract class for printing messages."""

    def print(self, message):
        raise NotImplementedError


class RealPrinter(Printer):
    """Implementation of `Printer` which uses `print` to output messages."""

    def print(self, message):
        print(message)


@autowired()
class PrintService:
    # RealPrinter will be automatically injected on property access.
    printer: Printer

    def run(self, msg):
        self.printer.print(f"{msg}, i'm running!")


if __name__ == "__main__":
    container = ContainerProvider.get()
    # Register RealPrinter as singleton implementation of Printer.
    container.register(Printer, RealPrinter())

    PrintService().run('hey')
$ python example.py
hey, i'm running!

注释

此库基于punq(MIT许可协议)构建,并使用其 vendored 版本。

项目详情


下载文件

下载您平台上的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分布

wint-0.2.0.tar.gz (6.4 kB 查看散列值)

上传时间 源码

构建版本

wint-0.2.0-py3-none-any.whl (23.6 kB 查看散列值)

上传时间 Python 3

由以下机构支持