2020-08-13 00:04:46 +03:00
|
|
|
.. _selector-provider:
|
|
|
|
|
2020-09-02 04:58:13 +03:00
|
|
|
Selector provider
|
2020-09-03 00:33:02 +03:00
|
|
|
=================
|
2020-06-29 23:32:12 +03:00
|
|
|
|
2020-09-02 04:39:23 +03:00
|
|
|
.. meta::
|
|
|
|
:keywords: Python,DI,Dependency injection,IoC,Inversion of Control,Configuration,Injection,
|
|
|
|
Selector,Polymorphism,Environment Variable,Flexibility
|
|
|
|
:description: Selector selects provider based on a configuration value or another callable.
|
|
|
|
This page demonstrates how to implement the polymorphism and increase the
|
|
|
|
flexibility of your application using the Selector provider.
|
|
|
|
|
2020-06-29 23:32:12 +03:00
|
|
|
.. currentmodule:: dependency_injector.providers
|
|
|
|
|
2020-09-02 04:39:23 +03:00
|
|
|
:py:class:`Selector` provider selects provider based on a configuration value or another callable.
|
2020-06-29 23:32:12 +03:00
|
|
|
|
|
|
|
.. literalinclude:: ../../examples/providers/selector.py
|
|
|
|
:language: python
|
2020-09-02 04:39:23 +03:00
|
|
|
:lines: 3-
|
2020-09-04 00:38:52 +03:00
|
|
|
:emphasize-lines: 16-20
|
2020-06-29 23:32:12 +03:00
|
|
|
|
2020-09-02 04:39:23 +03:00
|
|
|
The first argument of the ``Selector`` provider is called ``selector``. It can be an option of
|
|
|
|
a ``Configuration`` provider or any other callable. The ``selector`` callable has to return a
|
|
|
|
string value. This value is used as a key for selecting the provider.
|
2020-06-29 23:32:12 +03:00
|
|
|
|
2020-09-02 04:39:23 +03:00
|
|
|
The providers are provided as keyword arguments. Argument name is used as a key for selecting the
|
|
|
|
provider.
|
2020-06-29 23:32:12 +03:00
|
|
|
|
2020-09-02 04:39:23 +03:00
|
|
|
When a ``Selector`` provider is called, it gets a ``selector`` value and delegates the work to
|
|
|
|
the provider with a matching name. The ``selector`` callable works as a switch: when the returned
|
|
|
|
value is changed the ``Selector`` provider will delegate the work to another provider.
|
2020-06-29 23:32:12 +03:00
|
|
|
|
2022-01-10 05:45:20 +03:00
|
|
|
.. seealso::
|
|
|
|
:ref:`aggregate-provider` to inject a group of providers.
|
|
|
|
|
2020-06-29 23:32:12 +03:00
|
|
|
.. disqus::
|