From 8806405f0fb774d1ff7756a1cfe8b7ae89216530 Mon Sep 17 00:00:00 2001 From: Roman Mogylatov Date: Thu, 18 Feb 2021 08:38:35 -0500 Subject: [PATCH] Add docs on @containers.copy() decorator --- docs/containers/copying.rst | 14 +++++++++ docs/containers/index.rst | 1 + docs/main/changelog.rst | 1 + .../containers/declarative_copy_decorator.py | 31 +++++++++++++++++++ 4 files changed, 47 insertions(+) create mode 100644 docs/containers/copying.rst create mode 100644 examples/containers/declarative_copy_decorator.py diff --git a/docs/containers/copying.rst b/docs/containers/copying.rst new file mode 100644 index 00000000..5f403838 --- /dev/null +++ b/docs/containers/copying.rst @@ -0,0 +1,14 @@ +Container copying +----------------- + +You can create declarative container copies using ``@containers.copy()`` decorator. + +.. literalinclude:: ../../examples/containers/declarative_copy_decorator.py + :language: python + :lines: 3- + :emphasize-lines: 18-22 + +Decorator ``@containers.copy()`` copies providers from source container to destination container. +Destination container provider will replace source provider, if names match. + +.. disqus:: diff --git a/docs/containers/index.rst b/docs/containers/index.rst index f014b3c0..61de72fc 100644 --- a/docs/containers/index.rst +++ b/docs/containers/index.rst @@ -23,6 +23,7 @@ Containers module API docs - :py:mod:`dependency_injector.containers`. dynamic specialization overriding + copying reset_singletons check_dependencies traversal diff --git a/docs/main/changelog.rst b/docs/main/changelog.rst index 0999b589..808fafe4 100644 --- a/docs/main/changelog.rst +++ b/docs/main/changelog.rst @@ -9,6 +9,7 @@ follows `Semantic versioning`_ Development version ------------------- +- Add docs on ``@containers.copy()`` decorator. - Refactor ``@containers.copy()`` decorator. - Refactor async mode support in containers module. diff --git a/examples/containers/declarative_copy_decorator.py b/examples/containers/declarative_copy_decorator.py new file mode 100644 index 00000000..18fada24 --- /dev/null +++ b/examples/containers/declarative_copy_decorator.py @@ -0,0 +1,31 @@ +"""Declarative container provider copying with ``@copy()`` decorator.""" + +import sqlite3 +from unittest import mock + +from dependency_injector import containers, providers + + +class Service: + def __init__(self, db): + self.db = db + + +class SourceContainer(containers.DeclarativeContainer): + + database = providers.Singleton(sqlite3.connect, ':memory:') + service = providers.Factory(Service, db=database) + + +# Copy ``SourceContainer`` providers into ``DestinationContainer``: +@containers.copy(SourceContainer) +class DestinationContainer(SourceContainer): + + database = providers.Singleton(mock.Mock) + + +if __name__ == '__main__': + container = DestinationContainer() + + service = container.service() + assert isinstance(service.db, mock.Mock)