python-dependency-injector/examples/callable_provider.py

45 lines
1.1 KiB
Python
Raw Normal View History

2015-03-10 01:54:05 +03:00
"""Callable provider examples."""
2015-01-28 01:48:33 +03:00
from objects import AbstractCatalog
2015-03-10 01:54:05 +03:00
from objects.providers import Singleton
from objects.providers import Callable
from objects.injections import InitArg
from objects.injections import Attribute
from objects.injections import Injection
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,
InitArg('database', ':memory:'),
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,
Injection('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