Let's say my object needs to use an API to communicate with a device. The API call that I need is Api.do_something().
What would be the best way to solve this assuming that I need to call it only once? I'm inclined to use the third option but isn't dependency injection really too much of a hassle when I only need to call it once? The simplest solution is the first one, but then I have to mock Api().do_something() every time my test uses do_stuff(). On the other hand with the dependency injection I have to supply a stub object anyway.
1)
class MyObject(object):
def do_stuff():
return Api().do_something()
2)
class MyObject(object):
def __init__():
self.api = Api()
def do_stuff():
return self.api.do_something()
3)
class MyObject(object):
def __init__(api):
self.api = api
def do_stuff():
return self.api.do_something()