Callable providers

Callable provider calls wrapped callable on every call.

Callable providers and injections

Callable provider takes a various number of positional and keyword arguments that are used as wrapped callable injections. Every time, when Callable provider is called, positional and keyword argument injections would be passed as an callable arguments.

Injections are done according to the next rules:

  • All providers (instances of Provider) are called every time when injection needs to be done.
  • Providers could be injected “as is” (delegated), if it is defined obviously. Check out Callable providers delegation.
  • All other injectable values are provided “as is”.
  • Positional context arguments will be appended after Callable positional injections.
  • Keyword context arguments have priority on Callable keyword injections and will be merged over them.

Example that shows usage of Callable with positional argument injections:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
"""`Callable` providers with positional arguments example."""

import dependency_injector.providers as providers


# Creating even and odd filter providers:
even_filter = providers.Callable(filter, lambda x: x % 2 == 0)
odd_filter = providers.Callable(filter, lambda x: x % 2 != 0)

# Creating even and odd ranges using range() and filter providers:
even_range = even_filter(range(1, 10))
odd_range = odd_filter(range(1, 10))

# Making some asserts:
assert even_range == [2, 4, 6, 8]
assert odd_range == [1, 3, 5, 7, 9]

Next one example shows usage of Callable with keyword argument injections:

../_images/callable.png
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
"""`Callable` providers with keyword arguments example."""

import passlib.hash

import dependency_injector.providers as providers


# Password hasher and verifier providers:
password_hasher = providers.Callable(passlib.hash.sha256_crypt.encrypt,
                                     salt_size=16,
                                     rounds=10000)
password_verifier = providers.Callable(passlib.hash.sha256_crypt.verify)

# Making some asserts:
hashed_password = password_hasher('super secret')
assert password_verifier('super secret', hashed_password)

Callable providers delegation

Callable provider could be delegated to any other provider via any kind of injection.

Delegation of Callable providers is the same as Factory providers delegation, please follow Factory providers delegation section for examples (with exception of using DelegatedCallable instead of DelegatedFactory).

Abstract callable providers

AbstractCallable provider is a Callable provider that must be explicitly overridden before calling.

Behaviour of AbstractCallable providers is the same as of AbstractFactory, please follow Abstract factory providers section for examples (with exception of using AbstractCallable provider instead of AbstractFactory).