Skip to content

Instantly share code, notes, and snippets.

@uppfinnarjohnny
Created April 14, 2012 16:59
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save uppfinnarjohnny/2385916 to your computer and use it in GitHub Desktop.
Save uppfinnarjohnny/2385916 to your computer and use it in GitHub Desktop.
Simple DI Container for Python, inspired by Pimple (http://pimple.sensiolabs.org/)
class Container(dict):
def __init__(self, *args, **kwargs):
super(Container, self).__init__(*args, **kwargs)
self._shared = set()
self._instances = {}
def __getitem__(self, key):
if key in self._instances:
return self._instances[key]
value = super(Container, self).__getitem__(key)
value = value(self) if callable(value) else value
if key in self._shared:
self._instances[key] = value
return value
def share(self, key):
self._shared.add(key)
class Database(object):
def __init__(self, *args):
pass
container = Container()
container['db_user'] = 'root'
container['db_pass'] = '123'
container['db_host'] = 'localhost'
container['db'] = lambda c: Database(c['db_user'], c['db_pass'], c['db_host'])
container.share('db')
database = container['db']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment