mirror of
https://github.com/ets-labs/python-dependency-injector.git
synced 2025-07-04 20:33:13 +03:00
Add example and docs
This commit is contained in:
parent
da70d7511f
commit
57b69ee196
23
docs/providers/dict.rst
Normal file
23
docs/providers/dict.rst
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
Dict provider
|
||||||
|
=============
|
||||||
|
|
||||||
|
.. meta::
|
||||||
|
:keywords: Python,DI,Dependency injection,IoC,Inversion of Control,Dict,Injection
|
||||||
|
:description: Dict provider helps to inject a dictionary of the dependencies. This page demonstrates
|
||||||
|
how to use Dict provider.
|
||||||
|
|
||||||
|
.. currentmodule:: dependency_injector.providers
|
||||||
|
|
||||||
|
:py:class:`Dict` provider provides a dictionary of values.
|
||||||
|
|
||||||
|
.. literalinclude:: ../../examples/providers/dict.py
|
||||||
|
:language: python
|
||||||
|
:lines: 3-
|
||||||
|
:emphasize-lines: 21-24
|
||||||
|
|
||||||
|
``Dict`` provider handles keyword arguments the same way as a :ref:`factory-provider`.
|
||||||
|
|
||||||
|
.. note::
|
||||||
|
Positional argument are not supported.
|
||||||
|
|
||||||
|
.. disqus::
|
|
@ -43,6 +43,7 @@ Providers module API docs - :py:mod:`dependency_injector.providers`
|
||||||
coroutine
|
coroutine
|
||||||
object
|
object
|
||||||
list
|
list
|
||||||
|
dict
|
||||||
configuration
|
configuration
|
||||||
selector
|
selector
|
||||||
dependency
|
dependency
|
||||||
|
|
45
examples/providers/dict.py
Normal file
45
examples/providers/dict.py
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
"""`Dict` provider example."""
|
||||||
|
|
||||||
|
import dataclasses
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
from dependency_injector import containers, providers
|
||||||
|
|
||||||
|
|
||||||
|
@dataclasses.dataclass
|
||||||
|
class Module:
|
||||||
|
name: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclasses.dataclass
|
||||||
|
class Dispatcher:
|
||||||
|
modules: Dict[str, Module]
|
||||||
|
|
||||||
|
|
||||||
|
class Container(containers.DeclarativeContainer):
|
||||||
|
|
||||||
|
dispatcher_factory = providers.Factory(
|
||||||
|
Dispatcher,
|
||||||
|
modules=providers.Dict(
|
||||||
|
module1=providers.Factory(Module, name='m1'),
|
||||||
|
module2=providers.Factory(Module, name='m2'),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
container = Container()
|
||||||
|
|
||||||
|
dispatcher = container.dispatcher_factory()
|
||||||
|
|
||||||
|
assert isinstance(dispatcher.modules, dict)
|
||||||
|
assert dispatcher.modules['module1'].name == 'm1'
|
||||||
|
assert dispatcher.modules['module2'].name == 'm2'
|
||||||
|
|
||||||
|
# Call "dispatcher = container.dispatcher_factory()" is equivalent to:
|
||||||
|
# dispatcher = Dispatcher(
|
||||||
|
# modules={
|
||||||
|
# 'module1': Module(name='m1'),
|
||||||
|
# 'module2': Module(name='m2'),
|
||||||
|
# },
|
||||||
|
# )
|
Loading…
Reference in New Issue
Block a user