Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save irfanandriansyah1997/ae9b7c7a0c76d015ed72eeb0b949ccf8 to your computer and use it in GitHub Desktop.

Select an option

Save irfanandriansyah1997/ae9b7c7a0c76d015ed72eeb0b949ccf8 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