python - 如何在 Python 3.8 中为基类使用带引号的类型注释?
问题描述
假设我想创建一个这样的类:
class foo(dict[str, str]):
pass
Pyright 正确地强调[]
下标会导致运行时错误:
Python 3.8.7 (default, Jan 9 2021, 01:55:12)
[Clang 9.0.0 (tags/RELEASE_900/final)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class foo(dict[str, str]):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
这在 Python 3.9 中已修复,但不幸的是我被困在 Python 3.8 上。参数的正常解决方案是在类型周围添加引号,如下所示:
x: "dict[str, str]" = ...
但是我不知道如何使用基类来做到这一点。这些都不起作用:
class foo("dict[str, str]"):
pass
class foo(dict: "dict[str, str]"):
pass
可能吗?
解决方案
不,那些行不通。基类必须是实际类型,并且不能用:
语法进行注释。
在 Python 3.8 中,您应该只使用typing
模块中的类型:
from typing import Dict
class foo(Dict[str, str]):
pass
推荐阅读
- java - 实体对象未持久存在于 H2 数据库中
- git - 无法将现有代码推送到新的 git 存储库
- python - 极坐标图 - 将一条网格线以粗体显示
- wpf - 如何在 TreeView 用户控件中定义 TreeViewItem 触发器
- react-native - 在 React Native 中使用 Redux 更新抽屉导航
- c# - 带有 maphilight 的 ASP.NET C# ImageMap
- asp.net-core - 在一对多关系中获取价值(EF Core)
- nginx - Nginx 服务没有被 certbot 正确停止,因此不会重新启动
- swift - 移除 SKAction 并恢复节点状态
- scala - 在 scala 中设置处理