Skip to content
Advertisement

How to do dependency injection python-way?

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.

Advertisement

Answer

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:

JavaScript

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:

JavaScript

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:

JavaScript

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement