python代码依赖注入
pycdi的Python项目详细描述
一个简单的python cdi(代码依赖注入)库。
安装
安装稳定的pycdi
pip install pycdi
安装最新的pycdi
pip install git+https://github.com/ettoreleandrotognoli/python-cdi
用法
Python2和Python3
您可以在examples文件夹中看到更多示例(examples/common)。
importloggingfromloggingimportLoggerfrompycdiimportInject,Singleton,Producerfrompycdi.shortcutsimportcall@Producer(str,_context='app_name')defget_app_name():return'PyCDI'@Singleton(produce_type=Logger)@Inject(app_name=str,_context='app_name')defget_logger(app_name):returnlogging.getLogger(app_name)@Inject(name=(str,'app_name'),logger=Logger)defmain(name,logger):logger.info('I\'m starting...')print('Hello World!!!\nI\'m a example of %s'%name)logger.debug('I\'m finishing...')call(main)
Python3
使用python 3可以用类型提示定义注入的类型。
您可以在examples文件夹(examples/py3/)中看到更多示例。
importloggingfromloggingimportLoggerfrompycdiimportInject,Singleton,Producerfrompycdi.shortcutsimportcall@Producer(_context='app_name')defget_app_name()->str:return'PyCDI'@Singleton()@Inject(logger_name='app_name')defget_logger(logger_name:str)->Logger:returnlogging.getLogger(logger_name)@Inject(name='app_name')defmain(name:str,logger:Logger):logger.info('I\'m starting...')print('Hello World!!!\nI\'m a example of %s'%name)logger.debug('I\'m finishing...')call(main)