Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add multibind class provider #197

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ coverage.xml
/dist/
/injector.egg-info/
/.coverage
venv/
20 changes: 20 additions & 0 deletions injector/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,17 @@ def __repr__(self) -> str:
return '%s(%r)' % (type(self).__name__, self._providers)


@private
class ClassListProvider(Provider[List[T]]):
"""Provides a list of instances from a given class."""

def __init__(self, cls: Type[T]) -> None:
self._cls = cls

def get(self, injector: 'Injector') -> List[T]:
return [injector.create_object(self._cls)]


class MultiBindProvider(ListOfProviders[List[T]]):
"""Used by :meth:`Binder.multibind` to flatten results of providers that
return sequences."""
Expand All @@ -377,6 +388,15 @@ def get(self, injector: 'Injector') -> List[T]:
return [i for provider in self._providers for i in provider.get(injector)]


class MultiBindClassProvider(MultiBindProvider):
"""A provider for a list of instances from a list of classes."""

def __init__(self, classes: List[Type[T]]) -> None:
super().__init__()
for cls in classes:
self.append(ClassListProvider(cls))


class MapBindProvider(ListOfProviders[Dict[str, T]]):
"""A provider for map bindings."""

Expand Down
13 changes: 13 additions & 0 deletions injector_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
Binder,
CallError,
Injector,
MultiBindClassProvider,
Scope,
InstanceProvider,
ClassProvider,
Expand Down Expand Up @@ -473,6 +474,14 @@ def provide_description(self, age: int, weight: float) -> str:


def test_multibind():
class A:
def print(self) -> str:
return 'A'

class B(A):
def print(self) -> str:
return 'B'

# First let's have some explicit multibindings
def configure(binder):
binder.multibind(List[str], to=['not a name'])
Expand All @@ -483,6 +492,8 @@ def configure(binder):
# To see that NewTypes are treated distinctly
binder.multibind(Names, to=['Bob'])
binder.multibind(Passwords, to={'Bob': 'password1'})
# To see that MultiBindClassProvider works for lists of types
binder.multibind(List[A], to=MultiBindClassProvider([A, B]))

# Then @multiprovider-decorated Module methods
class CustomModule(Module):
Expand Down Expand Up @@ -517,6 +528,8 @@ def provide_passwords(self) -> Passwords:
assert injector.get(Dict[str, int]) == {'weight': 12, 'height': 33}
assert injector.get(Names) == ['Bob', 'Alice', 'Clarice']
assert injector.get(Passwords) == {'Bob': 'password1', 'Alice': 'aojrioeg3', 'Clarice': 'clarice30'}
assert injector.get(List[A])[0].print() == 'A'
assert injector.get(List[A])[1].print() == 'B'


def test_regular_bind_and_provider_dont_work_with_multibind():
Expand Down