python-dependency-injector/examples/callable_provider.py

43 lines
1.1 KiB
Python
Raw Normal View History

2015-03-10 01:54:05 +03:00
"""Callable provider examples."""
from objects.catalog import AbstractCatalog
2015-03-10 01:54:05 +03:00
from objects.providers import Singleton
from objects.providers import Callable
from objects.injections import KwArg
2015-03-10 01:54:05 +03:00
from objects.injections import Attribute
2015-01-28 01:48:33 +03:00
import sqlite3
def consuming_function(arg, db):
2015-03-10 01:54:05 +03:00
"""Example function that has input arg and dependency on database."""
2015-01-28 01:48:33 +03:00
return arg, db
class Catalog(AbstractCatalog):
2015-03-10 01:54:05 +03:00
"""Catalog of objects providers."""
2015-01-28 01:48:33 +03:00
database = Singleton(sqlite3.Connection,
KwArg('database', ':memory:'),
2015-01-28 01:48:33 +03:00
Attribute('row_factory', sqlite3.Row))
2015-03-10 01:54:05 +03:00
""":type: (objects.Provider) -> sqlite3.Connection"""
2015-01-28 01:48:33 +03:00
consuming_function = Callable(consuming_function,
KwArg('db', database))
2015-03-10 01:54:05 +03:00
""":type: (objects.Provider) -> consuming_function"""
2015-01-28 01:48:33 +03:00
# Some calls.
arg1, db1 = Catalog.consuming_function(1)
arg2, db2 = Catalog.consuming_function(2)
arg3, db3 = Catalog.consuming_function(3)
# Some asserts.
assert db1 is db2 is db3
assert arg1 == 1
assert arg2 == 2
assert arg3 == 3