python-dependency-injector/docs/containers/traversal.rst
Roman Mogylatov 3ca6dd9af1
Providers traversal (#385)
* Implement providers traversal in first precision

* Implement traversal for all providers

* Update traverse interface + add some tests

* Refactor tests

* Add tests for callable provider

* Add configuration tests

* Add Factory tests

* Add FactoryAggrefate tests

* Add .provides attribute to singleton providers

* Add singleton provider tests

* Add list and dict provider tests

* Add resource tests

* Add Container provider tests

* Add Selector provider tests

* Add ProvidedInstance provider tests

* Add AttributeGetter provider tests

* Add ItemGetter provider tests

* Add MethodCaller provider tests

* Refactor container interface

* Update resource provider string representation

* Add .initializer attribute to Resource provider

* Add docs and examples

* Remove not needed EOL in the tests

* Make cosmetic refactoring

* Ignore flake8 line width error in traverse example
2021-02-01 09:42:21 -05:00

34 lines
1.1 KiB
ReStructuredText

Container providers traversal
-----------------------------
To traverse container providers use method ``.traverse()``.
.. literalinclude:: ../../examples/containers/traverse.py
:language: python
:lines: 3-
:emphasize-lines: 38
Method ``.traverse()`` returns a generator. Traversal generator visits all container providers.
This includes nested providers even if they are not present on the root level of the container.
Traversal generator guarantees that each container provider will be visited only once.
It can traverse cyclic provider graphs.
Traversal generator does not guarantee traversal order.
You can use ``types=[...]`` argument to filter providers. Traversal generator will only return
providers matching specified types.
.. code-block:: python
:emphasize-lines: 3
container = Container()
for provider in container.traverse(types=[providers.Resource]):
print(provider)
# <dependency_injector.providers.Resource(<function init_database at 0x10bd2cb80>) at 0x10d346b40>
# <dependency_injector.providers.Resource(<function init_cache at 0x10be373a0>) at 0x10d346bc0>
.. disqus::