mirror of
https://github.com/ets-labs/python-dependency-injector.git
synced 2025-06-17 03:53:14 +03:00
53 lines
1.3 KiB
ReStructuredText
53 lines
1.3 KiB
ReStructuredText
.. _fastdepends-example:
|
|
|
|
FastDepends example
|
|
===================
|
|
|
|
.. meta::
|
|
:keywords: Python,Dependency Injection,FastDepends,Example
|
|
:description: This example demonstrates a usage of the FastDepends and Dependency Injector.
|
|
|
|
|
|
This example shows how to use ``Dependency Injector`` with `FastDepends <https://github.com/Lancetnik/FastDepends>`_.
|
|
|
|
Example code is available on `Github <https://github.com/ets-labs/python-dependency-injector/tree/master/tests/unit/wiringfastdepends>`_.
|
|
|
|
Quick sample
|
|
------------
|
|
|
|
Just use it within ``Depends``
|
|
|
|
.. code-block:: python
|
|
|
|
import sys
|
|
|
|
from dependency_injector import containers, providers
|
|
from dependency_injector.wiring import inject, Provide
|
|
from fast_depends import Depends
|
|
|
|
|
|
class CoefficientService:
|
|
@staticmethod
|
|
def get_coefficient() -> float:
|
|
return 1.2
|
|
|
|
|
|
class Container(containers.DeclarativeContainer):
|
|
service = providers.Factory(CoefficientService)
|
|
|
|
|
|
@inject
|
|
def apply_coefficient(
|
|
a: int,
|
|
coefficient_provider: CoefficientService = Depends(Provide[Container.service]),
|
|
) -> float:
|
|
return a * coefficient_provider.get_coefficient()
|
|
|
|
|
|
container = Container()
|
|
container.wire(modules=[sys.modules[__name__]])
|
|
|
|
apply_coefficient(100) == 120.0
|
|
|
|
|