Created
June 11, 2013 16:02
-
-
Save alecthomas/5758156 to your computer and use it in GitHub Desktop.
Example of Injector assisted injection using @provides.
This file contains 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
from injector import * | |
class Session(object): | |
def __init__(self, key, site): | |
self.key = key | |
self.site = site | |
SessionKey = Key('SessionKey') | |
class Site(object): | |
def __init__(self, url): | |
self.url = url | |
def __repr__(self): | |
return 'Site(%r)' % self.url | |
class SomeModule(Module): | |
def configure(self, binder): | |
binder.bind(SessionKey, to='foo') | |
@provides(Session) | |
@inject(key=SessionKey) | |
def provides_session(self, key, site): | |
return Session(key, site) | |
injector = Injector([SomeModule]) | |
session_builder = injector.get(AssistedBuilder(Session)) | |
foo = Site('foo.com') | |
session = session_builder.build(site=foo) | |
assert session.site is foo | |
print session.key, session.site |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment