python - Mypy 列表阴影

标签 python django-rest-framework type-hinting mypy python-typing

我有一个带有一些方法的 DRF (django-rest-framework) ViewSet 类,其中之一是

def foobar(foo: list[str], bar: list[int]) -> bool:
    return ...

今天,当我实现公共(public)ViewSet classdef list方法时,mypy 开始考虑这个新函数,而不是 list[str] 的内置列表,这给了我一些错误:

error: Function "path.to.the.class.list" is not valid as a type  [valid-type]
note: Perhaps you need "Callable[...]" or a callback protocol?
error: "list?[builtins.str]" has no attribute "__iter__" (not iterable)  [attr-defined]

问题很清楚,新函数会进行阴影处理。 问题是你通常如何避免这个问题? 就我个人而言,找到解决方案非常简单,我可以将我的函数移动到该类之外的另一个类/文件/,一切都会按预期工作。

我想收集其他想法。

最佳答案

第一个选择是不要对自定义对象使用内置名称。如果不可能,请使用

消除歧义
import builtins

builtins.list[str]

ClassName.list(视情况而定)

关于python - Mypy 列表阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69104779/

相关文章:

python - 无法解析应用条件语句的某些信息

python - lambda 的意外结果

函数签名的 Python 3 类型提示

Python程序如何计算字母c出现的次数

ios - 如何连接(GET请求)ios应用程序到django rest框架

Django REST Framework : when to create a hyperlinked resource and when nested resource? 如何发布嵌套资源?

python - 无法让 Django Rest Framework ViewSet 识别用户的权限

python - 文字和枚举的重载类型提示在 PyCharm 中不起作用

python - 如何从 Annotated 中读取扩展注释?

python - 在 GLUE 任务上微调 BERT 时,如何监控训练和评估损失?