diff --git a/README.rst b/README.rst index 61cff790..264553e5 100644 --- a/README.rst +++ b/README.rst @@ -109,19 +109,9 @@ your application objects when you apply dependency injection principle: .. code-block:: python from dependency_injector import containers, providers + from unittest import mock - - class ApiClient: - - def __init__(self, api_key: str, timeout: int): - self.api_key = api_key - self.timeout = timeout - - - class Service: - - def __init__(self, api_client: ApiClient): - self.api_client = api_client + from .example_di import ApiClient, Service class Container(containers.DeclarativeContainer): @@ -145,9 +135,12 @@ your application objects when you apply dependency injection principle: container.config.from_yaml('config.yml') service = container.service() - assert isinstance(service.api_client, ApiClient) + with container.api_client.override(mock.Mock()): + service = container.service() + assert isinstance(service.api_client, mock.Mock) + `More examples `_ Installation diff --git a/examples/di_demo2/demo.py b/examples/di_demo2/demo.py index 886b0de1..d0e2cb9a 100644 --- a/examples/di_demo2/demo.py +++ b/examples/di_demo2/demo.py @@ -1,18 +1,7 @@ from dependency_injector import containers, providers from unittest import mock - -class ApiClient: - - def __init__(self, api_key: str, timeout: int): - self.api_key = api_key - self.timeout = timeout - - -class Service: - - def __init__(self, api_client: ApiClient): - self.api_client = api_client +from .example_di import ApiClient, Service class Container(containers.DeclarativeContainer): @@ -41,4 +30,3 @@ if __name__ == '__main__': with container.api_client.override(mock.Mock()): service = container.service() assert isinstance(service.api_client, mock.Mock) - diff --git a/examples/di_demo2/example_di.py b/examples/di_demo2/example_di.py new file mode 100644 index 00000000..2a4bb423 --- /dev/null +++ b/examples/di_demo2/example_di.py @@ -0,0 +1,13 @@ + + +class ApiClient: + + def __init__(self, api_key: str, timeout: int): + self.api_key = api_key + self.timeout = timeout + + +class Service: + + def __init__(self, api_client: ApiClient): + self.api_client = api_client diff --git a/examples/di_demo2/example_no_di.py b/examples/di_demo2/example_no_di.py new file mode 100644 index 00000000..28ca034e --- /dev/null +++ b/examples/di_demo2/example_no_di.py @@ -0,0 +1,14 @@ +import os + + +class ApiClient: + + def __init__(self): + self.api_key = os.getenv('API_KEY') + self.timeout = os.getenv('TIMEOUT') + + +class Service: + + def __init__(self): + self.api_client = ApiClient()