Add example and docs

This commit is contained in:
Roman Mogylatov 2020-11-20 17:57:33 -05:00
parent 034e4814da
commit fbaf35244c
2 changed files with 80 additions and 2 deletions

View File

@ -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::

View File

@ -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(),
# },
# )