fastapi的依赖()原因是“不兼容的参数默认值”。 mypy错误
我有这个示例代码。
def get_test(q: str) -> str:
return 'str str str' + q
@router_user.put(
"/", response_model=schemas.UpdateUserRequest, tags=["User and Authentication"]
)
async def update_user(
data: schemas.UpdateUserRequest,
q: str = Depends(logic.get_test),
db: AsyncSession = Depends(get_db),
user: models.User = Depends(logic.get_curr_user_by_token),
):
print(q)
在用mypy检查时,我总是会遇到错误
app/api/user/router.py:74: error: Incompatible default for argument "q" (default has type "Depends", argument has type "str") [assignment]
I have this example code.
def get_test(q: str) -> str:
return 'str str str' + q
@router_user.put(
"/", response_model=schemas.UpdateUserRequest, tags=["User and Authentication"]
)
async def update_user(
data: schemas.UpdateUserRequest,
q: str = Depends(logic.get_test),
db: AsyncSession = Depends(get_db),
user: models.User = Depends(logic.get_curr_user_by_token),
):
print(q)
when checking it with mypy, I always get an error
app/api/user/router.py:74: error: Incompatible default for argument "q" (default has type "Depends", argument has type "str") [assignment]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来您使用了不正确的导入。
我已经清理了您的代码示例并添加了导入,并且以下确实通过了
mypy
:但是,如果我替换导入,
那么我会得到您从mypy遇到的相同错误。
我猜想您的IDE错误地从
fastapi.params
而不是直接从fastapi
中完成导入。如果您检查官方 docs ,您会看到该>依赖性
应直接从fastapi
直接导入。为什么发生这种情况
params.decide
是定义的类在这里。但是,如果您直接使用它,则每当您编写x:str = deweds(...)
之类的内容时,它将是类型错误,因为params.deppers.deppers.depperss.deppers
class class与str
不兼容。我们真正想要的是Mypy忽略依赖的类型()
,并假定其与任何类型兼容。这就是为什么
in
fastapi
实际上是围绕params.depends
“ nofollow noreferrer”>定义为 返回返回 yy 。It looks like you've used an incorrect import.
I've cleaned up your code sample and added imports, and the following does pass
mypy
:However, if I replace the imports with
Then I get the same error you got from mypy.
I'm guessing your IDE incorrectly completed the import from
fastapi.params
instead of directly fromfastapi
. If you check the official docs, you'll see thatDepends
should be imported directly fromfastapi
.Why this happens
params.Depends
is a class defined here. However, if you use that directly, it will be a type error whenever you write something likex: str = Depends(...)
, because theparams.Depends
class is not compatible withstr
. What we really want is for mypy to ignore the type ofDepends()
and assume it's compatible with any type.That's why the
Depends
infastapi
is actually a wrapper function aroundparams.Depends
defined as returningAny
.查看您的代码看起来像您的
get_curr_user_by_token
返回models.user
。依赖
本身不会改变结果的类型,因此您只需使用依赖
内的事物返回的结果。Looking at your code it looks like your
get_curr_user_by_token
returnsmodels.User
.Depends
itself doesn't change the type of result, so you just use the one that is returned by thing insideDepends
.