python-dependency-injector/examples/scoped_provider.py

72 lines
1.9 KiB
Python
Raw Normal View History

2015-01-28 01:21:31 +03:00
"""
Scoped provider examples.
"""
from objects import AbstractCatalog
from objects.providers import Singleton, Scoped
from objects.injections import InitArg, Attribute
2015-01-28 01:26:38 +03:00
2015-01-28 01:21:31 +03:00
import sqlite3
class ObjectA(object):
def __init__(self, db):
self.db = db
# Catalog of objects providers.
class Catalog(AbstractCatalog):
"""
Objects catalog.
"""
database = Singleton(sqlite3.Connection,
InitArg('database', ':memory:'),
Attribute('row_factory', sqlite3.Row))
""" :type: (objects.Provider) -> sqlite3.Connection """
object_a = Scoped(ObjectA,
InitArg('db', database))
""" :type: (objects.Provider) -> ObjectA """
2015-01-28 01:26:38 +03:00
# Making scope using `with` statement.
2015-01-28 01:21:31 +03:00
with Catalog.object_a as object_a_provider:
object_a1 = object_a_provider()
object_a2 = object_a_provider()
assert object_a1 is object_a2
assert object_a1.db is object_a2.db
2015-01-28 01:26:38 +03:00
# Making another one scope using `with` statement.
2015-01-28 01:21:31 +03:00
with Catalog.object_a as object_a_provider:
object_a3 = object_a_provider()
object_a4 = object_a_provider()
assert object_a3 is object_a4
assert object_a3.db is object_a4.db
assert (object_a1 is not object_a3) and \
(object_a1 is not object_a4)
assert (object_a2 is not object_a3) and \
(object_a2 is not object_a4)
2015-01-28 01:26:38 +03:00
# Making one more scope using provider methods.
2015-01-28 01:21:31 +03:00
Catalog.object_a.in_scope()
object_a5 = Catalog.object_a()
object_a6 = Catalog.object_a()
assert object_a5 is object_a6
assert object_a5.db is object_a6.db
assert (object_a1 is not object_a3) and \
(object_a1 is not object_a4) and \
(object_a1 is not object_a5) and \
(object_a1 is not object_a6)
assert (object_a2 is not object_a3) and \
(object_a2 is not object_a4) and \
(object_a2 is not object_a5) and \
(object_a2 is not object_a6)