2016-03-30 17:10:43 +03:00
|
|
|
Dependency injection and inversion of control in Python
|
2020-09-10 00:39:49 +03:00
|
|
|
=======================================================
|
2016-03-30 17:10:43 +03:00
|
|
|
|
2016-04-11 23:16:46 +03:00
|
|
|
.. meta::
|
2020-09-10 00:39:49 +03:00
|
|
|
:keywords: Python,DI,Dependency injection,IoC,Inversion of Control,Example
|
2020-09-10 00:53:00 +03:00
|
|
|
:description: This page describes a usage of the dependency injection and inversion of control
|
|
|
|
in Python. It contains Python examples that show how to implement dependency
|
|
|
|
injection. It demonstrates a usage of the dependency injection framework
|
2020-09-10 00:39:49 +03:00
|
|
|
Dependency Injector, its container, Factory, Singleton and Configuration
|
|
|
|
providers. The example show how to use Dependency Injector providers overriding
|
|
|
|
feature for testing or configuring project in different environments and explains
|
2021-05-21 00:58:15 +03:00
|
|
|
why it's better than monkey-patching.
|
2016-04-26 13:14:39 +03:00
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
Originally dependency injection pattern got popular in languages with static typing like Java.
|
|
|
|
Dependency injection is a principle that helps to achieve an inversion of control. A
|
|
|
|
dependency injection framework can significantly improve the flexibility of a language
|
|
|
|
with static typing. Implementation of a dependency injection framework for a language
|
|
|
|
with static typing is not something that one can do quickly. It will be a quite complex thing
|
2020-09-10 00:39:49 +03:00
|
|
|
to be done well. And will take time.
|
2016-04-26 13:14:39 +03:00
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
Python is an interpreted language with dynamic typing. There is an opinion that dependency
|
2020-09-10 00:39:49 +03:00
|
|
|
injection doesn't work for it as well as it does for Java. A lot of the flexibility is already
|
2022-04-17 05:29:19 +03:00
|
|
|
built-in. Also, there is an opinion that a dependency injection framework is something that
|
2020-09-10 00:39:49 +03:00
|
|
|
Python developer rarely needs. Python developers say that dependency injection can be implemented
|
|
|
|
easily using language fundamentals.
|
2016-04-26 13:14:39 +03:00
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
This page describes the advantages of applying dependency injection in Python. It
|
|
|
|
contains Python examples that show how to implement dependency injection. It demonstrates the usage
|
|
|
|
of the ``Dependency Injector`` framework, its container, ``Factory``, ``Singleton``,
|
|
|
|
and ``Configuration`` providers. The example shows how to use providers' overriding feature
|
|
|
|
of ``Dependency Injector`` for testing or re-configuring a project in different environments and
|
2021-05-21 00:58:15 +03:00
|
|
|
explains why it's better than monkey-patching.
|
2016-04-26 13:14:39 +03:00
|
|
|
|
2020-09-10 00:39:49 +03:00
|
|
|
What is dependency injection?
|
|
|
|
-----------------------------
|
2016-04-26 13:14:39 +03:00
|
|
|
|
2020-09-10 00:39:49 +03:00
|
|
|
Let's see what the dependency injection is.
|
2016-04-26 13:14:39 +03:00
|
|
|
|
2020-09-10 00:39:49 +03:00
|
|
|
Dependency injection is a principle that helps to decrease coupling and increase cohesion.
|
2016-04-26 13:14:39 +03:00
|
|
|
|
2020-09-10 00:39:49 +03:00
|
|
|
.. image:: images/coupling-cohesion.png
|
|
|
|
|
|
|
|
What is coupling and cohesion?
|
|
|
|
|
|
|
|
Coupling and cohesion are about how tough the components are tied.
|
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
- **High coupling**. If the coupling is high it's like using superglue or welding. No easy way
|
2020-09-10 00:39:49 +03:00
|
|
|
to disassemble.
|
2022-04-17 05:29:19 +03:00
|
|
|
- **High cohesion**. High cohesion is like using screws. Quite easy to disassemble and
|
|
|
|
re-assemble in a different way. It is an opposite to high coupling.
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
Cohesion often correlates with coupling. Higher cohesion usually leads to lower coupling and vice versa.
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
Low coupling brings flexibility. Your code becomes easier to change and test.
|
2020-09-10 00:39:49 +03:00
|
|
|
|
|
|
|
How to implement the dependency injection?
|
|
|
|
|
|
|
|
Objects do not create each other anymore. They provide a way to inject the dependencies instead.
|
|
|
|
|
|
|
|
Before:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
import os
|
|
|
|
|
|
|
|
|
|
|
|
class ApiClient:
|
|
|
|
|
2022-04-17 04:29:35 +03:00
|
|
|
def __init__(self) -> None:
|
2021-09-30 22:03:19 +03:00
|
|
|
self.api_key = os.getenv("API_KEY") # <-- dependency
|
2022-04-17 04:29:35 +03:00
|
|
|
self.timeout = int(os.getenv("TIMEOUT")) # <-- dependency
|
2020-09-10 00:39:49 +03:00
|
|
|
|
|
|
|
|
|
|
|
class Service:
|
|
|
|
|
2022-04-17 04:29:35 +03:00
|
|
|
def __init__(self) -> None:
|
2020-10-09 22:16:27 +03:00
|
|
|
self.api_client = ApiClient() # <-- dependency
|
2020-09-10 00:39:49 +03:00
|
|
|
|
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
def main() -> None:
|
|
|
|
service = Service() # <-- dependency
|
|
|
|
...
|
|
|
|
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2021-09-30 22:03:19 +03:00
|
|
|
if __name__ == "__main__":
|
2020-10-09 22:16:27 +03:00
|
|
|
main()
|
2020-09-10 00:39:49 +03:00
|
|
|
|
|
|
|
After:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
import os
|
|
|
|
|
|
|
|
|
|
|
|
class ApiClient:
|
|
|
|
|
2022-04-17 04:29:35 +03:00
|
|
|
def __init__(self, api_key: str, timeout: int) -> None:
|
2020-10-09 22:16:27 +03:00
|
|
|
self.api_key = api_key # <-- dependency is injected
|
|
|
|
self.timeout = timeout # <-- dependency is injected
|
2020-09-10 00:39:49 +03:00
|
|
|
|
|
|
|
|
|
|
|
class Service:
|
|
|
|
|
2022-04-17 04:29:35 +03:00
|
|
|
def __init__(self, api_client: ApiClient) -> None:
|
2020-10-09 22:16:27 +03:00
|
|
|
self.api_client = api_client # <-- dependency is injected
|
|
|
|
|
|
|
|
|
2022-04-17 04:29:35 +03:00
|
|
|
def main(service: Service) -> None: # <-- dependency is injected
|
2020-10-09 22:16:27 +03:00
|
|
|
...
|
2020-09-10 00:39:49 +03:00
|
|
|
|
|
|
|
|
2021-09-30 22:03:19 +03:00
|
|
|
if __name__ == "__main__":
|
2020-10-09 22:16:27 +03:00
|
|
|
main(
|
|
|
|
service=Service(
|
|
|
|
api_client=ApiClient(
|
2021-09-30 22:03:19 +03:00
|
|
|
api_key=os.getenv("API_KEY"),
|
2022-04-17 04:29:35 +03:00
|
|
|
timeout=int(os.getenv("TIMEOUT")),
|
2020-10-09 22:16:27 +03:00
|
|
|
),
|
|
|
|
),
|
|
|
|
)
|
2020-09-10 00:39:49 +03:00
|
|
|
|
|
|
|
``ApiClient`` is decoupled from knowing where the options come from. You can read a key and a
|
|
|
|
timeout from a configuration file or even get them from a database.
|
|
|
|
|
|
|
|
``Service`` is decoupled from the ``ApiClient``. It does not create it anymore. You can provide a
|
|
|
|
stub or other compatible object.
|
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
Function ``main()`` is decoupled from ``Service``. It receives it as an argument.
|
|
|
|
|
2020-09-10 00:39:49 +03:00
|
|
|
Flexibility comes with a price.
|
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
Now you need to assemble and inject the objects like this:
|
|
|
|
|
|
|
|
.. code-block:: python
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
main(
|
|
|
|
service=Service(
|
|
|
|
api_client=ApiClient(
|
2021-09-30 22:03:19 +03:00
|
|
|
api_key=os.getenv("API_KEY"),
|
2022-04-17 04:29:35 +03:00
|
|
|
timeout=int(os.getenv("TIMEOUT")),
|
2020-10-09 22:16:27 +03:00
|
|
|
),
|
|
|
|
),
|
|
|
|
)
|
2020-09-10 00:39:49 +03:00
|
|
|
|
|
|
|
The assembly code might get duplicated and it'll become harder to change the application structure.
|
|
|
|
|
|
|
|
Here comes the ``Dependency Injector``.
|
|
|
|
|
|
|
|
What does the Dependency Injector do?
|
|
|
|
-------------------------------------
|
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
With the dependency injection pattern, objects lose the responsibility of assembling
|
2021-12-21 01:46:51 +03:00
|
|
|
the dependencies. The ``Dependency Injector`` absorbs that responsibility.
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
``Dependency Injector`` helps to assemble and inject the dependencies.
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
It provides a container and providers that help you with the objects assembly.
|
|
|
|
When you need an object you place a ``Provide`` marker as a default value of a
|
2022-04-17 05:29:19 +03:00
|
|
|
function argument. When you call this function, framework assembles and injects
|
2020-10-09 22:16:27 +03:00
|
|
|
the dependency.
|
2020-09-10 00:39:49 +03:00
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
from dependency_injector import containers, providers
|
2021-09-30 22:03:19 +03:00
|
|
|
from dependency_injector.wiring import Provide, inject
|
2020-09-10 00:39:49 +03:00
|
|
|
|
|
|
|
|
|
|
|
class Container(containers.DeclarativeContainer):
|
|
|
|
|
|
|
|
config = providers.Configuration()
|
|
|
|
|
|
|
|
api_client = providers.Singleton(
|
|
|
|
ApiClient,
|
|
|
|
api_key=config.api_key,
|
2021-12-21 01:46:51 +03:00
|
|
|
timeout=config.timeout,
|
2020-09-10 00:39:49 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
service = providers.Factory(
|
|
|
|
Service,
|
|
|
|
api_client=api_client,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2020-11-16 00:06:42 +03:00
|
|
|
@inject
|
2022-04-17 04:29:35 +03:00
|
|
|
def main(service: Service = Provide[Container.service]) -> None:
|
2020-10-09 22:16:27 +03:00
|
|
|
...
|
|
|
|
|
|
|
|
|
2021-09-30 22:03:19 +03:00
|
|
|
if __name__ == "__main__":
|
2020-09-10 00:39:49 +03:00
|
|
|
container = Container()
|
2021-12-21 01:46:51 +03:00
|
|
|
container.config.api_key.from_env("API_KEY", required=True)
|
|
|
|
container.config.timeout.from_env("TIMEOUT", as_=int, default=5)
|
2021-09-30 22:03:19 +03:00
|
|
|
container.wire(modules=[__name__])
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
main() # <-- dependency is injected automatically
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2020-10-09 22:16:27 +03:00
|
|
|
with container.api_client.override(mock.Mock()):
|
|
|
|
main() # <-- overridden dependency is injected automatically
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
When you call the ``main()`` function the ``Service`` dependency is assembled and injected automatically.
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
When you do testing, you call the ``container.api_client.override()`` method to replace the real API
|
|
|
|
client with a mock. When you call ``main()``, the mock is injected.
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2020-09-10 05:23:14 +03:00
|
|
|
You can override any provider with another provider.
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
It also helps you in a re-configuring project for different environments: replace an API client
|
2020-09-10 00:39:49 +03:00
|
|
|
with a stub on the dev or stage.
|
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
Objects assembling is consolidated in a container. Dependency injections are defined explicitly.
|
|
|
|
This makes it easier to understand and change how an application works.
|
2020-10-09 22:16:27 +03:00
|
|
|
|
2020-09-10 00:39:49 +03:00
|
|
|
Testing, Monkey-patching and dependency injection
|
|
|
|
-------------------------------------------------
|
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
The testability benefit is opposed to monkey-patching.
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
In Python, you can monkey-patch anything, anytime. The problem with monkey-patching is
|
|
|
|
that it's too fragile. The cause of it is that when you monkey-patch you do something that
|
|
|
|
wasn't intended to be done. You monkey-patch the implementation details. When implementation
|
|
|
|
changes the monkey-patching is broken.
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
With dependency injection, you patch the interface, not an implementation. This is a way more
|
2020-09-10 00:39:49 +03:00
|
|
|
stable approach.
|
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
Also, monkey-patching is way too dirty to be used outside of the testing code for
|
|
|
|
re-configuring the project for the different environments.
|
2020-09-10 00:39:49 +03:00
|
|
|
|
|
|
|
Conclusion
|
2020-09-10 00:59:44 +03:00
|
|
|
----------
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
Dependency injection provides you with three advantages:
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
- **Flexibility**. The components are loosely coupled. You can easily extend or change the
|
|
|
|
functionality of a system by combining the components in a different way. You even can do it on
|
2020-09-10 00:39:49 +03:00
|
|
|
the fly.
|
2022-04-17 05:29:19 +03:00
|
|
|
- **Testability**. Testing is easier because you can easily inject mocks instead of real objects
|
2020-09-10 00:39:49 +03:00
|
|
|
that use API or database, etc.
|
|
|
|
- **Clearness and maintainability**. Dependency injection helps you reveal the dependencies.
|
2020-09-10 06:34:59 +03:00
|
|
|
Implicit becomes explicit. And "Explicit is better than implicit" (PEP 20 - The Zen of Python).
|
2022-04-17 05:29:19 +03:00
|
|
|
You have all the components and dependencies defined explicitly in a container. This
|
|
|
|
provides an overview and control of the application structure. It is easier to understand and
|
2020-09-10 00:39:49 +03:00
|
|
|
change it.
|
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
Is it worth applying dependency injection in Python?
|
2020-09-10 00:39:49 +03:00
|
|
|
|
|
|
|
It depends on what you build. The advantages above are not too important if you use Python as a
|
|
|
|
scripting language. The picture is different when you use Python to create an application. The
|
2022-04-17 05:29:19 +03:00
|
|
|
larger the application the more significant the benefits.
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
Is it worth using a framework for applying dependency injection?
|
2020-09-10 00:39:49 +03:00
|
|
|
|
|
|
|
The complexity of the dependency injection pattern implementation in Python is
|
2022-04-17 05:29:19 +03:00
|
|
|
lower than in other languages but it's still in place. It doesn't mean you have to use a
|
2020-09-10 00:39:49 +03:00
|
|
|
framework but using a framework is beneficial because the framework is:
|
|
|
|
|
|
|
|
- Already implemented
|
|
|
|
- Tested on all platforms and versions of Python
|
|
|
|
- Documented
|
|
|
|
- Supported
|
2022-04-17 05:29:19 +03:00
|
|
|
- Other engineers are familiar with it
|
2020-09-10 00:39:49 +03:00
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
An advice at last:
|
2020-09-10 00:39:49 +03:00
|
|
|
|
|
|
|
- **Give it a try**. Dependency injection is counter-intuitive. Our nature is that
|
|
|
|
when we need something the first thought that comes to our mind is to go and get it. Dependency
|
2022-04-17 05:29:19 +03:00
|
|
|
injection is just like "Wait, I need to state a need instead of getting something right away".
|
2020-09-10 00:39:49 +03:00
|
|
|
It's like a little investment that will pay-off later. The advice is to just give it a try for
|
|
|
|
two weeks. This time will be enough for getting your own impression. If you don't like it you
|
|
|
|
won't lose too much.
|
2022-04-17 05:29:19 +03:00
|
|
|
- **Common sense first**. Use common sense when applying dependency injection. It is a good
|
|
|
|
principle, but not a silver bullet. If you do it too much you will reveal too many of the
|
2020-09-10 00:39:49 +03:00
|
|
|
implementation details. Experience comes with practice and time.
|
2017-02-28 23:00:08 +03:00
|
|
|
|
2020-07-20 23:58:18 +03:00
|
|
|
What's next?
|
2020-09-10 00:39:49 +03:00
|
|
|
------------
|
2020-07-20 23:58:18 +03:00
|
|
|
|
|
|
|
Choose one of the following as a next step:
|
|
|
|
|
2020-09-10 00:39:49 +03:00
|
|
|
- Look at the application examples:
|
2020-09-05 06:19:32 +03:00
|
|
|
- :ref:`application-single-container`
|
|
|
|
- :ref:`application-multiple-containers`
|
2020-09-08 05:06:59 +03:00
|
|
|
- :ref:`decoupled-packages`
|
2021-03-01 16:28:22 +03:00
|
|
|
- :ref:`boto3-example`
|
2020-10-09 22:16:27 +03:00
|
|
|
- :ref:`django-example`
|
|
|
|
- :ref:`flask-example`
|
2020-11-16 02:07:57 +03:00
|
|
|
- :ref:`flask-blueprints-example`
|
2020-10-09 22:16:27 +03:00
|
|
|
- :ref:`aiohttp-example`
|
|
|
|
- :ref:`sanic-example`
|
2020-11-16 00:06:42 +03:00
|
|
|
- :ref:`fastapi-example`
|
2021-01-11 03:26:15 +03:00
|
|
|
- :ref:`fastapi-redis-example`
|
2021-02-05 02:18:25 +03:00
|
|
|
- :ref:`fastapi-sqlalchemy-example`
|
2020-09-05 06:19:32 +03:00
|
|
|
- Pass the tutorials:
|
|
|
|
- :ref:`flask-tutorial`
|
|
|
|
- :ref:`aiohttp-tutorial`
|
|
|
|
- :ref:`asyncio-daemon-tutorial`
|
|
|
|
- :ref:`cli-tutorial`
|
2020-09-10 00:39:49 +03:00
|
|
|
- Know more about the ``Dependency Injector`` :ref:`key-features`
|
2020-09-05 06:19:32 +03:00
|
|
|
- Know more about the :ref:`providers`
|
2020-10-09 22:16:27 +03:00
|
|
|
- Know more about the :ref:`wiring`
|
2020-09-05 06:19:32 +03:00
|
|
|
- Go to the :ref:`contents`
|
2020-07-20 23:58:18 +03:00
|
|
|
|
2019-06-07 16:55:30 +03:00
|
|
|
Useful links
|
2020-09-10 00:39:49 +03:00
|
|
|
------------
|
2017-05-29 10:19:23 +03:00
|
|
|
|
2022-04-17 05:29:19 +03:00
|
|
|
A few useful links related to a dependency injection design pattern for further reading:
|
2017-05-29 10:19:23 +03:00
|
|
|
|
|
|
|
+ https://en.wikipedia.org/wiki/Dependency_injection
|
|
|
|
+ https://martinfowler.com/articles/injection.html
|
|
|
|
+ https://github.com/ets-labs/python-dependency-injector
|
2020-01-27 04:32:16 +03:00
|
|
|
+ https://pypi.org/project/dependency-injector/
|
2017-02-28 23:00:08 +03:00
|
|
|
|
|
|
|
.. disqus::
|