Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple DI Container for Python, inspired by Pimple (
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):
class Database(object):
def __init__(self, *args):
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'])
database = container['db']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.