Skip to content

How it works

At first, I suppose, we need to discuss about this tool's key concept.

It is very simple:

  1. At your code's initialization time FastDepends builds special pydantic model with your function's expected arguments as a model fields, builds the dependencies graph
  2. At runtime FastDepends grabs all incoming functions' *args, **kwargs and initializes functions' representation models with them
  3. At the next step FastDepends execute functions' dependensies with the model fields as an arguments, calls the original function
  4. Finally, FastDepends catches functions' outputs and casts it to expected return type

This is pretty close to the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from pydantic import BaseModel
from fast_depends import Depends

def simple_dependency(a: int, **kwargs):
    return a

def my_function(a: int, b: int, d = Depends(simple_dependency)) -> float:
    return a + b + d

# Declare function representation model
class MyFunctionRepresentation(BaseModel):
    a: int
    b: int

args, kwargs = (), {"a": 1, "b": "3"}

# Cast incomint arguments
arguments_model = MyFunctionRepresentation(**kwargs)

# Use them
new_kwargs = arguments_model.dict()
base_response = my_function(
    **new_kwargs,
    d=simple_dependency(**new_kwargs)
)

class ResponseModel(BaseModel):
    field: float

# Cast response
real_response = ResponseModel(field=base_response).field

Note

It is not the real code, but generally FastDepends works this way

So, the biggest part of the FastDepends code execution happens on application startup. At runtime the library just casts types to already built models. It works really fast. Generally, the library works with the same speed as the pydantic - the main dependency.

On the other hand, working with only *args, **kwargs allows the library to be independent from other frameworks, business domains, technologies, etc. You are free to decide for yourself, how exactly to use this tool.