Skip to content

Commit 86df7f9

Browse files
authored
531 Provider import from string (ets-labs#555)
* Implement string imports for Factory, Callable, Singletons, and Resource * Refactor the implementation * Add tests * Update tests to pass on Python 2 * Update typing and add typing tests * Update changelog * Update docs
1 parent 38ca1cd commit 86df7f9

File tree

15 files changed

+10021
-8754
lines changed

15 files changed

+10021
-8754
lines changed

docs/main/changelog.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ Development version
2121
``FactoryAggregate.factories`` attribute.
2222
- Add ``.set_providers()`` method to the ``FactoryAggregate`` provider. It is an alias for
2323
``FactoryAggregate.set_factories()`` method.
24+
- Add string imports for ``Factory``, ``Singleton``, ``Callable``, ``Resource``, and ``Coroutine``
25+
providers, e.g. ``Factory("module.Class")``.
26+
See issue `#531 <https://github.com/ets-labs/python-dependency-injector/issues/531>`_.
27+
Thanks to `@al-stefanitsky-mozdor <https://github.com/al-stefanitsky-mozdor>`_ for suggesting the feature.
2428
- Fix ``Dependency`` provider to don't raise "Dependency is not defined" error when the ``default``
2529
is a falsy value of proper type.
2630
See issue `#550 <https://github.com/ets-labs/python-dependency-injector/issues/550>`_. Thanks to

docs/providers/factory.rst

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,45 @@ attribute of the provider that you're going to inject.
110110

111111
.. note:: Any provider has a ``.provider`` attribute.
112112

113+
.. _factory-string-imports:
114+
115+
String imports
116+
--------------
117+
118+
``Factory`` provider can handle string imports:
119+
120+
.. code-block:: python
121+
122+
class Container(containers.DeclarativeContainer):
123+
124+
service = providers.Factory("myapp.mypackage.mymodule.Service")
125+
126+
You can also make a relative import:
127+
128+
.. code-block:: python
129+
130+
# in myapp/container.py
131+
132+
class Container(containers.DeclarativeContainer):
133+
134+
service = providers.Factory(".mypackage.mymodule.Service")
135+
136+
or import a member of the current module just specifying its name:
137+
138+
.. code-block:: python
139+
140+
class Service:
141+
...
142+
143+
144+
class Container(containers.DeclarativeContainer):
145+
146+
service = providers.Factory("Service")
147+
148+
.. note::
149+
``Singleton``, ``Callable``, ``Resource``, and ``Coroutine`` providers handle string imports
150+
the same way as a ``Factory`` provider.
151+
113152
.. _factory-specialize-provided-type:
114153

115154
Specializing the provided type

0 commit comments

Comments
 (0)