2020-09-03 03:59:55 +03:00
|
|
|
"""Custom provider example."""
|
2015-07-28 01:29:31 +03:00
|
|
|
|
2020-09-03 03:59:55 +03:00
|
|
|
from dependency_injector import providers
|
2015-07-28 01:29:31 +03:00
|
|
|
|
|
|
|
|
2020-09-03 03:59:55 +03:00
|
|
|
class CustomFactory(providers.Provider):
|
2015-07-28 01:29:31 +03:00
|
|
|
|
|
|
|
__slots__ = ('_factory',)
|
|
|
|
|
2020-09-03 03:59:55 +03:00
|
|
|
def __init__(self, provides, *args, **kwargs):
|
|
|
|
self._factory = providers.Factory(provides, *args, **kwargs)
|
2020-01-27 02:41:36 +03:00
|
|
|
super().__init__()
|
2015-07-28 01:29:31 +03:00
|
|
|
|
2020-09-03 03:59:55 +03:00
|
|
|
def __deepcopy__(self, memo):
|
|
|
|
copied = memo.get(id(self))
|
|
|
|
if copied is not None:
|
|
|
|
return copied
|
|
|
|
|
|
|
|
copied = self.__class__(
|
|
|
|
self._factory.provides,
|
|
|
|
*providers.deepcopy(self._factory.args, memo),
|
|
|
|
**providers.deepcopy(self._factory.kwargs, memo),
|
|
|
|
)
|
|
|
|
self._copy_overridings(copied, memo)
|
2015-11-23 19:45:04 +03:00
|
|
|
|
2020-09-03 03:59:55 +03:00
|
|
|
return copied
|
|
|
|
|
|
|
|
def _provide(self, args, kwargs):
|
2015-07-28 01:29:31 +03:00
|
|
|
return self._factory(*args, **kwargs)
|
|
|
|
|
|
|
|
|
2020-09-03 03:59:55 +03:00
|
|
|
factory = CustomFactory(object)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
object1 = factory()
|
|
|
|
assert isinstance(object1, object)
|
2015-07-28 01:29:31 +03:00
|
|
|
|
2020-09-03 03:59:55 +03:00
|
|
|
object2 = factory()
|
|
|
|
assert isinstance(object1, object)
|
2015-07-28 01:29:31 +03:00
|
|
|
|
2020-09-03 03:59:55 +03:00
|
|
|
assert object1 is not object2
|