python-dependency-injector/examples/providers/provided_instance.py
Roman Mogylatov cf862fe8b5
Provided attributes (#282)
* Add sketch

* Cythonize MethodCaller

* Cythonize ItemGetter, AttributeGetter & ProvidedInstance providers

* Add docblock for .provided attribute

* Refactor repr methods

* Add .provided attribute to the Dependency provider

* Add tests for the .provided attribute to the majority of the providers

* Add docblock for the ProvidedInstance provider

* Add docblocks for the rest of the providers

* Add example of the provided instance usage

* Add tests for provided instance* providers

* Add complex provided instance example

* Update example provided_instance.py

* Add docs
2020-08-20 21:52:12 -04:00

39 lines
897 B
Python

"""Example of the injecting of provided instance attributes and items."""
from dependency_injector import providers
class Service:
def __init__(self):
self.value = 'foo'
self.values = [self.value]
def get_value(self):
return self.value
def __getitem__(self, item):
return self.values[item]
class Client:
def __init__(self, value1, value2, value3, value4):
self.value1 = value1
self.value2 = value2
self.value3 = value3
self.value4 = value4
service = providers.Singleton(Service)
client_factory = providers.Factory(
Client,
value1=service.provided[0],
value2=service.provided.value,
value3=service.provided.values[0],
value4=service.provided.get_value.call(),
)
if __name__ == '__main__':
client = client_factory()
assert client.value1 == client.value2 == client.value3 == 'foo'