Created
August 20, 2010 09:02
-
-
Save samuraisam/539926 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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