Is there a framework equivalent to Guice (http://code.google.com/p/google-guice) for Python?
Is there a framework equivalent to Guice (http://code.google.com/p/google-guice) for Python?
Spring Python is an offshoot of the Java-based Spring Framework and Spring Security, targeted for Python. This project currently contains the following features:
I haven't used it, but the Spring Python framework is based on Spring and implements Inversion of Control.
There also appears to be a Guice in Python project: snake-guice
As an alternative to monkeypatching, I like DI. A nascent project such as http://code.google.com/p/snake-guice/ may fit the bill.
Or see the blog post Dependency Injection in Python by Dennis Kempin (Aug '08).
I made a lib to do this https://github.com/ettoreleandrotognoli/python-cdi I hope that helps
It's available on pypi: https://pypi.python.org/pypi/pycdi
With it you can make injections with python2
import logging
from logging import Logger
from pycdi import Inject, Singleton, Producer
from pycdi.shortcuts import call
@Producer(str, _context='app_name')
def get_app_name():
return 'PyCDI'
@Singleton(produce_type=Logger)
@Inject(app_name=str, _context='app_name')
def get_logger(app_name):
return logging.getLogger(app_name)
@Inject(name=(str, 'app_name'), logger=Logger)
def main(name, logger):
logger.info('I\'m starting...')
print('Hello World!!!\nI\'m a example of %s' % name)
logger.debug('I\'m finishing...')
call(main)
And using type hints from python3
import logging
from logging import Logger
from pycdi import Inject, Singleton, Producer
from pycdi.shortcuts import call
@Producer(_context='app_name')
def get_app_name() -> str:
return 'PyCDI'
@Singleton()
@Inject(logger_name='app_name')
def get_logger(logger_name: str) -> Logger:
return logging.getLogger(logger_name)
@Inject(name='app_name')
def main(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)
Enterprython is a small framework providing dependency-injection, building the object graph automatically based on type hints.
Here's a good comparison (19 September 2020): Comparison of Dependency Injection Libraries in Python, and my favorite one
His winners are:
proofit404/dependencies (Injector) "simple, but provided all the necessary features. If you need something that’s not provided then just think about the design in your application, cause the flow might be somewhere there. Beautiful configuration. Perfect match for agile projects"
ets-labs/python-dependency-injector "very expanded library, with constant support, the problem is it’s boilerplate, if that does not bother you, then it’s a great choice"
I recently released a neat (IMHO) micro library for DI in python:
I'm actively developing pinject for Python >= 3.6. It's quite easy to use:
class MyObject:
my_service: MyService = INJECTED
my_config: str = INJECTED