Amend docs and add another example for ``@containers.copy()`` decorator

This commit is contained in:
Roman Mogylatov 2021-02-19 08:11:05 -05:00
parent 6a73b9d3fd
commit a85d89e6f2
3 changed files with 43 additions and 1 deletions

View File

@ -3,7 +3,7 @@ Container copying
You can create declarative container copies using ``@containers.copy()`` decorator.
.. literalinclude:: ../../examples/containers/declarative_copy_decorator.py
.. literalinclude:: ../../examples/containers/declarative_copy_decorator1.py
:language: python
:lines: 3-
:emphasize-lines: 18-22
@ -11,4 +11,13 @@ You can create declarative container copies using ``@containers.copy()`` decorat
Decorator ``@containers.copy()`` copies providers from source container to destination container.
Destination container provider will replace source provider, if names match.
Decorator ``@containers.copy()`` helps you when you create derived declarative containers
from the base one. Base container often keeps default dependencies while derived containers define
overriding providers. Without ``@containers.copy()`` decorator, overridden providers are available
in the derived container, but base class dependencies continue to be bound to the base class providers.
.. literalinclude:: ../../examples/containers/declarative_copy_decorator2.py
:language: python
:lines: 11-
.. disqus::

View File

@ -0,0 +1,33 @@
"""Declarative container provider copying with ``@copy()`` decorator."""
from dependency_injector import containers, providers
class Service:
def __init__(self, dependency: str):
self.dependency = dependency
class Base(containers.DeclarativeContainer):
dependency = providers.Dependency(instance_of=str, default='Default value')
service = providers.Factory(Service, dependency=dependency)
@containers.copy(Base)
class Derived1(Base):
dependency = providers.Dependency(instance_of=str, default='Derived 1')
# @containers.copy(Base) # <-- No @copy decorator
class Derived2(Base):
dependency = providers.Dependency(instance_of=str, default='Derived 2')
if __name__ == '__main__':
container1 = Derived1()
service1 = container1.service()
print(service1.dependency) # Derived 1
container2 = Derived2()
service2 = container2.service()
print(service2.dependency) # Default value