From fbaf35244cc92bd459046d6f8631d7ae3b1b790f Mon Sep 17 00:00:00 2001 From: Roman Mogylatov Date: Fri, 20 Nov 2020 17:57:33 -0500 Subject: [PATCH] Add example and docs --- docs/providers/dict.rst | 18 +++++- examples/providers/dict_non_string_keys.py | 64 ++++++++++++++++++++++ 2 files changed, 80 insertions(+), 2 deletions(-) create mode 100644 examples/providers/dict_non_string_keys.py diff --git a/docs/providers/dict.rst b/docs/providers/dict.rst index 45e07de3..bf62c4e6 100644 --- a/docs/providers/dict.rst +++ b/docs/providers/dict.rst @@ -17,7 +17,21 @@ Dict provider ``Dict`` provider handles keyword arguments the same way as a :ref:`factory-provider`. -.. note:: - Positional argument are not supported. +To use non-string keys or keys with ``.`` and ``-`` provide a dictionary as a positional argument: + +.. code-block:: python + + providers.Dict({ + SomeClass: providers.Factory(...), + 'key.with.periods': providers.Factory(...), + 'key-with-dashes': providers.Factory(...), + }) + +Example: + +.. literalinclude:: ../../examples/providers/dict_non_string_keys.py + :language: python + :lines: 3- + :emphasize-lines: 40-43 .. disqus:: diff --git a/examples/providers/dict_non_string_keys.py b/examples/providers/dict_non_string_keys.py new file mode 100644 index 00000000..11c7a593 --- /dev/null +++ b/examples/providers/dict_non_string_keys.py @@ -0,0 +1,64 @@ +"""`Dict` provider with non-string keys example.""" + +import dataclasses +from typing import Dict + +from dependency_injector import containers, providers + + +class Command: + ... + + +class CommandA(Command): + ... + + +class CommandB(Command): + ... + + +class Handler: + ... + + +class HandlerA(Handler): + ... + + +class HandlerB(Handler): + ... + + +@dataclasses.dataclass +class Dispatcher: + command_handlers: Dict[Command, Handler] + + +class Container(containers.DeclarativeContainer): + + dispatcher_factory = providers.Factory( + Dispatcher, + command_handlers=providers.Dict({ + CommandA: providers.Factory(HandlerA), + CommandB: providers.Factory(HandlerB), + }), + ) + + +if __name__ == '__main__': + container = Container() + + dispatcher = container.dispatcher_factory() + + assert isinstance(dispatcher.command_handlers, dict) + assert isinstance(dispatcher.command_handlers[CommandA], HandlerA) + assert isinstance(dispatcher.command_handlers[CommandB], HandlerB) + + # Call "dispatcher = container.dispatcher_factory()" is equivalent to: + # dispatcher = Dispatcher( + # command_handlers={ + # CommandA: HandlerA(), + # CommandB: HandlerB(), + # }, + # )