Skip to content

Instantly share code, notes, and snippets.

@dstanek
Created July 21, 2014 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dstanek/94a4142a097c92cf9002 to your computer and use it in GitHub Desktop.
Save dstanek/94a4142a097c92cf9002 to your computer and use it in GitHub Desktop.
DI with snake-guice
import abc
class Logger(object):
__metaclass__ abc.ABCMeta
@abstractmethod
def log_it(self, message, *args, **kwargs):
raise NotImplemented
class FileLogger(Logger):
def __init__(self, filename):
self.filename = filename
def log_it(self, message, *args, **kwargs):
print 'logging to a file'
class EmailLogger(Logger):
def __init__(self, emailer):
self.emailer = emailer
def log_it(self, message, *args, **kwargs):
print 'logging to an email'
class Emailer(object):
def __init__(self, server):
self.server = server
def send(self, message):
pass
class DomainObject(object):
def __init__(self, logger):
self.logger = logger
def operation(self):
self.logger.log_it('message')
class FileModule:
def configure(self, binder):
binder.bind(Logger, to_instance=FileLogger('test.log'))
class EmailModule:
def configure(self, binder):
binder.bind(Logger, to=EmailLogger)
binder.bind(Emailer, to=Emailer) # this will happen implicitly anyway
d0 = Injector(FileModule()).get_instance(DomainObject)
d1 = Injector(EmailModule()).get_instance(DomainObject)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment