python - 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]
问题很清楚,新功能做了阴影。问题是你通常如何避免这个问题?在我个人的情况下,找到一个解决方案很容易,我可以将我的函数移动到另一个类/文件/这个类之外,一切都会按预期工作。
我想收集其他想法。
解决方案
第一选择是不要为自定义对象使用内置名称。如果这不可能,请消除歧义
import builtins
builtins.list[str]
或ClassName.list
酌情
推荐阅读
- powershell - Powershell - 根据第二个文件数据从文件中提取数据
- python - 尝试在默认 VPC 之外使用 Apache libcloud 部署 ec2 实例
- arrays - 基于关键字搜索字符串(不能比较多个关键字)VB.NET
- extjs - Extjs TreeStore,多个异步请求,treepanel渲染错位
- r - 为什么 R 中的 rle 返回不正确的长度?
- sql - 仅在目标表中定义外键时,如何将数据从一个表复制到另一个表?
- php - 同时捕获多个异常并为每个异常调用 get 方法以检索验证错误消息
- java - 通过 Flux Rest API 代理 WebClients 响应
- php - 我如何在 php 中将 4 组 0 和 1 与所有可能的 4 位数字组合结合起来?
- java - 在画布上仅显示图像的特定部分