Skip to content

Instantly share code, notes, and snippets.

@blaix
Created July 30, 2015 18:25
Show Gist options
  • Save blaix/cd99251e3a5e035ce5dd to your computer and use it in GitHub Desktop.
Save blaix/cd99251e3a5e035ce5dd to your computer and use it in GitHub Desktop.
Dependency injection example in python
class MySqlDb(object):
def run(self, query):
# whatever...
# ----------------------------------------------------------------------
# Here, Foo can get bars, AND knows exactly what db implementation to use:
class Foo:
def __init__(self):
self.db = MySqlDb()
def get_bars(self):
return self.db.run("select * from bars")
foo = Foo()
bars = foo.get_bars()
# ----------------------------------------------------------------------
# Here, Foo can only get bars, you have to give it a db to use.
# Makes it more flexible (and easier to test).
class Foo:
def __init__(self, db):
self.db = db
def get_bars(self):
return self.db.run("select * from bars")
db = MySqlDb()
foo = Foo(db)
bars = foo.get_bars()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment