我有一个带有一些方法的 DRF (django-rest-framework) ViewSet 类,其中之一是
def foobar(foo: list[str], bar: list[int]) -> bool:
return ...
今天,当我实现公共(public)ViewSet class的def 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/