FastAPI makes extensive use of the type annotations at runtime, which then requires that the relevant imports be available at runtime. This can cause issues when Ruff suggests they be moved into type-checking blocks.
Ruff has some configuration options which allows for these imports to be excluded from the type-checking block, such as:
One place which I think isn't covered is the argument to Depends and Security which allows FastAPI to execute functions in order to perform argument injection.
E.g.
def get_foo():
return "foo"
from .foo import get_foo
from fastapi import Depends
from typing import Annotated
def repeat_foo(foo: Annotated[str, Depends(get_foo)]):
return foo + foo
Now I may have missed an option that can then tell ruff that arguments to Depends should not be moved into the type-checking block. But if it is not currently possible, this may be a good improvement to add to ruff.
FastAPI makes extensive use of the type annotations at runtime, which then requires that the relevant imports be available at runtime. This can cause issues when Ruff suggests they be moved into type-checking blocks.
Ruff has some configuration options which allows for these imports to be excluded from the type-checking block, such as:
runtime-evaluated-base-classesruntime-evaluated-decoratorsOne place which I think isn't covered is the argument to
DependsandSecuritywhich allows FastAPI to execute functions in order to perform argument injection.E.g.
Now I may have missed an option that can then tell ruff that arguments to
Dependsshould not be moved into the type-checking block. But if it is not currently possible, this may be a good improvement to add to ruff.