带有类型提示的依赖注入
wint的Python项目详细描述
带有类型提示的wint依赖注入。
简介
wint是一个轻量级库,它通过类型提示实现依赖注入。
安装
只需使用pip:
$ pip install wint
工作原理
对di有很多方法,这个库只实现属性注入。
当应用autowired
decorator时,将检查所有类
带注释的属性。如果属性没有值,则将其替换为DependencyDescriptor
。
当在实例化的类实例上访问属性时,将解析依赖关系。
这种行为允许以懒洋洋的方式解决依赖关系,同时也带来了副作用实例的负面影响。 接收先前未存在的描述符属性。
示例
fromwintimportautowired,ContainerProviderclassPrinter:"""Abstract class for printing messages."""defprint(self,message):raiseNotImplementedErrorclassRealPrinter(Printer):"""Implementation of `Printer` which uses `print` to output messages."""defprint(self,message):print(message)@autowired()classPrintService:# RealPrinter will be automatically injected on property access.printer:Printerdefrun(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 (麻省理工学院许可证)并使用它的供应商版本。