From ffca0dac0fad5bf7b830d1414d223b9c28205d7f Mon Sep 17 00:00:00 2001 From: Roman Mogylatov Date: Thu, 6 Aug 2020 16:27:18 -0400 Subject: [PATCH] Add example --- .../providers/factory_deep_init_injections.py | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 examples/providers/factory_deep_init_injections.py diff --git a/examples/providers/factory_deep_init_injections.py b/examples/providers/factory_deep_init_injections.py new file mode 100644 index 00000000..0cc9fba7 --- /dev/null +++ b/examples/providers/factory_deep_init_injections.py @@ -0,0 +1,48 @@ +"""`Factory` providers deep init injections example.""" + +from dependency_injector import providers + + +class Regularizer: + def __init__(self, alpha): + self.alpha = alpha + + +class Loss: + def __init__(self, regularizer): + self.regularizer = regularizer + + +class ClassificationTask: + def __init__(self, loss): + self.loss = loss + + +class Algorithm: + def __init__(self, task): + self.task = task + + +algorithm_factory = providers.Factory( + Algorithm, + task=providers.Factory( + ClassificationTask, + loss=providers.Factory( + Loss, + regularizer=providers.Factory( + Regularizer, + ), + ), + ), +) + + +if __name__ == '__main__': + algorithm_1 = algorithm_factory(task__loss__regularizer__alpha=0.5) + assert algorithm_1.task.loss.regularizer.alpha == 0.5 + + algorithm_2 = algorithm_factory(task__loss__regularizer__alpha=0.7) + assert algorithm_2.task.loss.regularizer.alpha == 0.7 + + algorithm_3 = algorithm_factory(task__loss__regularizer=Regularizer(alpha=0.8)) + assert algorithm_3.task.loss.regularizer.alpha == 0.8