Skip to content

Instantly share code, notes, and snippets.

@alecthomas
Created June 11, 2013 16:02
Show Gist options
  • Save alecthomas/5758156 to your computer and use it in GitHub Desktop.
Save alecthomas/5758156 to your computer and use it in GitHub Desktop.
Example of Injector assisted injection using @provides.
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