Skip to content

Instantly share code, notes, and snippets.

@samuraisam
Created August 20, 2010 09:02
Show Gist options
  • Save samuraisam/539926 to your computer and use it in GitHub Desktop.
Save samuraisam/539926 to your computer and use it in GitHub Desktop.
"""
My dependency injection framework for Python. Using a context manager it allows
you to rewrite globals (such as imports, top-level classes and functions, whatever
you want) in a module and have them replaced at the end of the with block. This is
usually enough. `proxy` is just a dict-wrapping type class which will create a
type with "class variables" for every key you give it.
Usage:
from di import *
with inject(cf.publishers, g=proxy(db=self.db)):
for i, u in enumerate(data['urls']):
# a function that lives in cf.publishers
# and depends on a global database object
pub = next_publisher()
assert pub
pubs.append(pub)
>>>
"""
import contextlib
@contextlib.contextmanager
def inject(*mods, **data):
orig = {}
for mod in mods:
for k in data.keys():
orig[k] = getattr(mod, k)
setattr(mod, k, data[k])
yield
for mod in mods:
for k in orig.keys():
setattr(mod, k, orig[k])
def proxy(**kv):
return type('DictWrapper', (object,), kv)()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment