首页 > 解决方案 > Mypy 列表阴影

问题描述

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

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

今天,当我实现def list普通ViewSet 类的方法时,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]

问题很清楚,新功能做了阴影。问题是你通常如何避免这个问题?在我个人的情况下,找到一个解决方案很容易,我可以将我的函数移动到另一个类/文件/这个类之外,一切都会按预期工作。

我想收集其他想法。

标签: pythondjango-rest-frameworktype-hintingmypypython-typing

解决方案


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

import builtins

builtins.list[str]

ClassName.list酌情


推荐阅读