python-dependency-injector/examples/providers/aggregate.py
Roman Mogylatov 742e73af1a
Aggregate provider (#544)
* Add implementation and typing stubs

* Add tests

* Add typing tests

* Refactor FactoryAggregate

* Update changelog

* Add Aggregate provider docs and example

* Update cross links between Aggregate, Selector, and FactoryAggregate docs

* Add wording improvements to the docs
2022-01-09 21:45:20 -05:00

40 lines
867 B
Python

"""`Aggregate` provider example."""
from dependency_injector import containers, providers
class ConfigReader:
def __init__(self, path):
self._path = path
def read(self):
print(f"Parsing {self._path} with {self.__class__.__name__}")
...
class YamlReader(ConfigReader):
...
class JsonReader(ConfigReader):
...
class Container(containers.DeclarativeContainer):
config_readers = providers.Aggregate(
yaml=providers.Factory(YamlReader),
json=providers.Factory(JsonReader),
)
if __name__ == "__main__":
container = Container()
yaml_reader = container.config_readers("yaml", "./config.yml")
yaml_reader.read() # Parsing ./config.yml with YamlReader
json_reader = container.config_readers("json", "./config.json")
json_reader.read() # Parsing ./config.json with JsonReader