首页 > 解决方案 > 如何在 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

可能吗?

标签: pythontype-hinting

解决方案


不,那些行不通。基类必须是实际类型,并且不能用:语法进行注释。

在 Python 3.8 中,您应该只使用typing模块中的类型:

from typing import Dict

class foo(Dict[str, str]):
    pass

推荐阅读