DIPPY: Dependency Injection for Python
DIPPY is a simple dependency injection container for Python. It supports both constructor and 'setter' (actually direct attribute access) injection.
Furthermore I make a distinction between the following service types:
- Factory services - which exist to create multiple instances of objects. A factory service will fulfil dependencies of created objects, but allow other constructor arguments to be specified at creation time. The container provides an appropriately configured factory, and container clients actually instantiate the object themselves.
- Singleton services - which are managed by the container. Only a single instance will ever be created. Additional constructor arguments may be passed at registration time.
- Instance services - useful for things such as configuration settings, flags, strings etc. The container is provided with the object instance, rather than the class.
Example:
class Article:
constructor_dependencies = dict(db='database')
def __init__(db, id=None):
self.db = db
if id:
self.load(id)
container.register_service('db_password', 'very_s3cret')
container.register_service('db_host', '127.0.0.1')
container.register_service('db_user', 'mydbuser')
container.register_singleton_service('database', MysqlDatabase)
container.register_factory_service('article', Article)
a = container.article(id=234) # instantiate article id 234
Download: dippy.tgz
Acknowledgements:
- Marcus Baker (http://lastcraft.com), for telling me about DI in the first place
- Martin Fowler, for his fantastic article on DI:
http://www.martinfowler.com/articles/injection.html - Pico Container, for detailing the Patterns and Anti-patterns relating to DI
- Jim Weirich, for demonstrating an alternate approach to DI in dynamic languages:
http://onestepback.org/index.cgi/Tech/Ruby/DependencyInjectionInRuby.rdoc - Christian Neukirchen, Dissident, for a thought provoking approach to DI in ruby:
http://chneukirchen.org/blog/archive/2005/08/design-and-evolution-of-a-dependency-injection-framework.html