2015-11-23 16:45:04 +00:00
|
|
|
"""Custom `Factory` example."""
|
2015-07-27 22:29:31 +00:00
|
|
|
|
2016-06-06 08:54:05 +00:00
|
|
|
import dependency_injector.providers as providers
|
2015-07-27 22:29:31 +00:00
|
|
|
|
|
|
|
|
|
|
|
class User(object):
|
|
|
|
"""Example class User."""
|
|
|
|
|
|
|
|
|
2015-11-23 16:45:04 +00:00
|
|
|
class UsersFactory(providers.Provider):
|
2015-07-27 22:29:31 +00:00
|
|
|
"""Example users factory."""
|
|
|
|
|
|
|
|
__slots__ = ('_factory',)
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
"""Initializer."""
|
2015-11-23 16:45:04 +00:00
|
|
|
self._factory = providers.Factory(User)
|
2015-07-27 22:29:31 +00:00
|
|
|
super(UsersFactory, self).__init__()
|
|
|
|
|
2017-05-08 14:07:54 +00:00
|
|
|
def __call__(self, *args, **kwargs):
|
|
|
|
"""Return provided object.
|
2015-11-23 16:45:04 +00:00
|
|
|
|
2017-05-08 14:07:54 +00:00
|
|
|
Callable interface implementation.
|
2015-11-23 16:45:04 +00:00
|
|
|
"""
|
2017-05-08 14:07:54 +00:00
|
|
|
if self.last_overriding is not None:
|
|
|
|
return self.last_overriding._provide(args, kwargs)
|
2015-07-27 22:29:31 +00: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
|