2015-09-02 12:23:18 +03:00
|
|
|
"""Catalog overriding example."""
|
2015-08-04 17:05:34 +03:00
|
|
|
|
2015-09-02 00:24:19 +03:00
|
|
|
import collections
|
|
|
|
import dependency_injector as di
|
2015-08-04 17:05:34 +03:00
|
|
|
|
|
|
|
|
|
|
|
# Creating some example classes:
|
2015-09-02 00:24:19 +03:00
|
|
|
Object1 = collections.namedtuple('Object1', ['arg1', 'arg2'])
|
|
|
|
Object2 = collections.namedtuple('Object2', ['object1'])
|
|
|
|
ExtendedObject2 = collections.namedtuple('ExtendedObject2', [])
|
2015-08-04 17:05:34 +03:00
|
|
|
|
|
|
|
|
2015-11-10 11:42:29 +03:00
|
|
|
class Catalog(di.DeclarativeCatalog):
|
2015-08-04 17:05:34 +03:00
|
|
|
"""Providers catalog."""
|
|
|
|
|
2015-09-02 00:24:19 +03:00
|
|
|
object1_factory = di.Factory(Object1,
|
|
|
|
arg1=1,
|
|
|
|
arg2=2)
|
2015-10-26 13:52:52 +03:00
|
|
|
""":type: di.Provider -> Object1"""
|
2015-08-04 17:05:34 +03:00
|
|
|
|
2015-09-02 00:24:19 +03:00
|
|
|
object2_factory = di.Factory(Object2,
|
|
|
|
object1=object1_factory)
|
2015-10-26 13:52:52 +03:00
|
|
|
""":type: di.Provider -> Object2"""
|
2015-08-04 17:05:34 +03:00
|
|
|
|
|
|
|
|
2015-11-10 11:42:29 +03:00
|
|
|
class AnotherCatalog(di.DeclarativeCatalog):
|
2015-08-04 17:05:34 +03:00
|
|
|
"""Another providers catalog."""
|
|
|
|
|
2015-09-02 00:24:19 +03:00
|
|
|
object2_factory = di.Factory(ExtendedObject2)
|
2015-10-26 13:52:52 +03:00
|
|
|
""":type: di.Provider -> ExtendedObject2"""
|
2015-08-04 17:05:34 +03:00
|
|
|
|
|
|
|
|
|
|
|
# Overriding `Catalog` with `AnotherCatalog`:
|
|
|
|
Catalog.override(AnotherCatalog)
|
|
|
|
|
2015-09-02 00:24:19 +03:00
|
|
|
# Creating some objects using overridden catalog:
|
2015-08-04 17:05:34 +03:00
|
|
|
object2_1 = Catalog.object2_factory()
|
|
|
|
object2_2 = Catalog.object2_factory()
|
|
|
|
|
|
|
|
# Making some asserts:
|
|
|
|
assert object2_1 is not object2_2
|
|
|
|
|
|
|
|
assert isinstance(object2_1, ExtendedObject2)
|
|
|
|
assert isinstance(object2_2, ExtendedObject2)
|