views:

152

answers:

1

I've been reading a lot about python-way lately so my question is

How to do dependency injection python-way?

I am talking about usual scenarios when, for example, service A needs access to UserService for authorization checks.

+2  A: 

It all depends on the situation. For example, if you use dependency injection for testing purposes -- so you can easily mock out something -- you can often forgo injection altogether: you can instead mock out the module or class you would otherwise inject:

subprocess.Popen = some_mock_Popen
result = subprocess.call(...)
assert some_mock_popen.result == result

subprocess.call() will call subprocess.Popen(), and we can mock it out without having to inject the dependency in a special way. We can just replace subprocess.Popen directly. (This is just an example; in real life you would do this in a much more robust way.)

If you use dependency injection for more complex situations, or when mocking whole modules or classes isn't appropriate (because, for example, you want to only mock out one particular call) then using class attributes or module globals for the dependencies is the usual choice. For example, considering a my_subprocess.py:

from subprocess import Popen

def my_call(...):
    return Popen(...).communicate()

You can easily replace only the Popen call made by my_call() by assigning to my_subprocess.Popen; it wouldn't affect any other calls to subprocess.Popen (but it would replace all calls to my_subprocess.Popen, of course.) Similarly, class attributes:

class MyClass(object):
    Popen = staticmethod(subprocess.Popen)
    def call(self):
        return self.Popen(...).communicate(...)

When using class attributes like this, which is rarely necessary considering the options, you should take care to use staticmethod. If you don't, and the object you're inserting is a normal function object or another type of descriptor, like a property, that does something special when retrieved from a class or instance, it would do the wrong thing. Worse, if you used something that right now isn't a descriptor (like the subprocess.Popen class, in the example) it would work now, but if the object in question changed to a normal function future, it would break confusingly.

Lastly, there's just plain callbacks; if you just want to tie a particular instance of a class to a particular service, you can just pass the service (or one or more of the service's methods) to the class initializer, and have it use that:

class MyClass(object):
    def __init__(self, authenticate=None, authorize=None):
        if authenticate is None:
            authenticate = default_authenticate
        if authorize is None:
            authorize = default_authorize
        self.authenticate = authenticate
        self.authorize = authorize
    def request(self, user, password, action):
        self.authenticate(user, password)
        self.authorize(user, action)
        self._do_request(action)

...
helper = AuthService(...)
# Pass bound methods to helper.authenticate and helper.authorize to MyClass.
inst = MyClass(authenticate=helper.authenticate, authorize=helper.authorize)
inst.request(...)

When setting instance attributes like that, you never have to worry about descriptors firing, so just assigning the functions (or classes or other callables or instances) is fine.

Thomas Wouters
I have C# background so I am used to explicit injections via constructor and using Container to resolve everything. Specifying defaults to None in initializer looks like "poor man's DI" which doesn't look like the best practice to me as it's not explicit enough. Similar thoughts about replacing existing methods by assignment (is this what is called `monkey patching`?). Should I just change my mindset because python-way differs from C#-way?
Konstantin Spirin
Yes, if you want to write efficient, pythonic code, you should realize that Python is quite a different language. You do different things differently. Monkeypatching modules for testing is really very common and quite safe (especially when using a proper mocking library to handle the details for you.) Monkeypatching classes (changing specific methods on classes) is a different matter.The None defaults are really not the thing you should focus on -- that example is actually quite close to DI through the constructor, you can just omit the default and make it a required argument if you want.
Thomas Wouters