2015-11-23 19:45:04 +03:00
|
|
|
"""Custom `Factory` example."""
|
2015-07-28 01:29:31 +03:00
|
|
|
|
2016-06-06 11:54:05 +03:00
|
|
|
import dependency_injector.providers as providers
|
2015-07-28 01:29:31 +03:00
|
|
|
|
|
|
|
|
2020-01-27 02:41:36 +03:00
|
|
|
class User:
|
2015-07-28 01:29:31 +03:00
|
|
|
"""Example class User."""
|
|
|
|
|
|
|
|
|
2015-11-23 19:45:04 +03:00
|
|
|
class UsersFactory(providers.Provider):
|
2015-07-28 01:29:31 +03:00
|
|
|
"""Example users factory."""
|
|
|
|
|
|
|
|
__slots__ = ('_factory',)
|
|
|
|
|
|
|
|
def __init__(self):
|
2020-01-26 22:22:43 +03:00
|
|
|
"""Initialize instance."""
|
2015-11-23 19:45:04 +03:00
|
|
|
self._factory = providers.Factory(User)
|
2020-01-27 02:41:36 +03:00
|
|
|
super().__init__()
|
2015-07-28 01:29:31 +03:00
|
|
|
|
2017-05-08 17:07:54 +03:00
|
|
|
def __call__(self, *args, **kwargs):
|
|
|
|
"""Return provided object.
|
2015-11-23 19:45:04 +03:00
|
|
|
|
2017-05-08 17:07:54 +03:00
|
|
|
Callable interface implementation.
|
2015-11-23 19:45:04 +03:00
|
|
|
"""
|
2017-05-08 17:07:54 +03:00
|
|
|
if self.last_overriding is not None:
|
|
|
|
return self.last_overriding._provide(args, kwargs)
|
2015-07-28 01:29:31 +03:00
|
|
|
return self._factory(*args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
# Users factory:
|
|
|
|
users_factory = UsersFactory()
|
|
|
|
|
|
|
|
# Creating several User objects:
|
|
|
|
user1 = users_factory()
|
|
|
|
user2 = users_factory()
|
|
|
|
|
|
|
|
# Making some asserts:
|
|
|
|
assert isinstance(user1, User)
|
|
|
|
assert isinstance(user2, User)
|
|
|
|
assert user1 is not user2
|