2015-11-23 19:45:04 +03:00
|
|
|
"""Custom `Factory` example."""
|
2015-07-28 01:29:31 +03:00
|
|
|
|
2015-11-23 19:45:04 +03:00
|
|
|
from dependency_injector import providers
|
2015-07-28 01:29:31 +03:00
|
|
|
|
|
|
|
|
|
|
|
class User(object):
|
|
|
|
"""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):
|
|
|
|
"""Initializer."""
|
2015-11-23 19:45:04 +03:00
|
|
|
self._factory = providers.Factory(User)
|
2015-07-28 01:29:31 +03:00
|
|
|
super(UsersFactory, self).__init__()
|
|
|
|
|
|
|
|
def _provide(self, *args, **kwargs):
|
2015-11-23 19:45:04 +03:00
|
|
|
"""Return provided instance.
|
|
|
|
|
|
|
|
:param args: tuple of context positional arguments
|
|
|
|
:type args: tuple[object]
|
|
|
|
|
|
|
|
:param kwargs: dictionary of context keyword arguments
|
|
|
|
:type kwargs: dict[str, object]
|
|
|
|
|
|
|
|
:rtype: object
|
|
|
|
"""
|
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
|