Skip to content

Commit eb5344c

Browse files
committed
Document get_bindings
Might want to look into making pytest handle Sphinx-formatted doctests to reduce the code repetition here.
1 parent 9590ebd commit eb5344c

File tree

2 files changed

+53
-3
lines changed

2 files changed

+53
-3
lines changed

injector/__init__.py

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -863,14 +863,43 @@ def repr_key(k):
863863
return dependencies
864864

865865

866-
def get_bindings(callable):
866+
def get_bindings(callable: Callable) -> Dict[str, type]:
867+
"""Get bindings of injectable parameters from a callable.
868+
869+
If the callable is not decorated with :func:`inject` an empty dictionary will
870+
be returned. Otherwise the returned dictionary will contain a mapping
871+
between parameter names and their types with the exception of parameters
872+
excluded from dependency injection with :func:`noninjectable`. For example::
873+
874+
>>> def function1(a: int) -> None:
875+
... pass
876+
...
877+
>>> get_bindings(function1)
878+
{}
879+
>>> @inject
880+
... def function2(a: int) -> None:
881+
... pass
882+
...
883+
>>> get_bindings(function2)
884+
{'a': int}
885+
>>> @inject
886+
... @noninjectable('b')
887+
... def function3(a: int, b: str) -> None:
888+
... pass
889+
...
890+
>>> get_bindings(function3)
891+
{'a': int}
892+
893+
This function is used internally so by calling it you can learn what exactly
894+
Injector is going to try to provide to a callable.
895+
"""
867896
if not hasattr(callable, '__bindings__'):
868897
return {}
869898

870-
if callable.__bindings__ == 'deferred':
899+
if cast(Any, callable).__bindings__ == 'deferred':
871900
read_and_store_bindings(callable, _infer_injected_bindings(callable))
872901
noninjectables = getattr(callable, '__noninjectables__', set())
873-
return {k: v for k, v in callable.__bindings__.items() if k not in noninjectables}
902+
return {k: v for k, v in cast(Any, callable).__bindings__.items() if k not in noninjectables}
874903

875904

876905
class _BindingNotYetAvailable(Exception):

injector_test.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
Scope,
3030
InstanceProvider,
3131
ClassProvider,
32+
get_bindings,
3233
inject,
3334
multiprovider,
3435
noninjectable,
@@ -1417,3 +1418,23 @@ def configure(binder):
14171418

14181419
injector = Injector([configure])
14191420
assert injector.get(Data).name == 'data'
1421+
1422+
1423+
def test_get_bindings():
1424+
def function1(a: int) -> None:
1425+
pass
1426+
1427+
assert get_bindings(function1) == {}
1428+
1429+
@inject
1430+
def function2(a: int) -> None:
1431+
pass
1432+
1433+
assert get_bindings(function2) == {'a': int}
1434+
1435+
@inject
1436+
@noninjectable('b')
1437+
def function3(a: int, b: str) -> None:
1438+
pass
1439+
1440+
assert get_bindings(function3) == {'a': int}

0 commit comments

Comments
 (0)