首页 > 解决方案 > PyCharm 中文字类型检查错误的 Python 列表(与带有文字键的 dict 相同)

问题描述

我想在 Python 中使用 Literal 类型提示的优点,但似乎 Literal 没有被正确识别为 dict 键或列表:

from typing import Literal, Dict, List

T = Literal['foo', 'bar']
L = List[T]
D = Dict[T, int]

q: T = 'foo'  # ok
l: L = ['foo', 'bar']  # Expected type 'List[Literal['foo', 'bar']]', got 'List[str]' instead 
d: D = {'foo': 1}  # Expected type 'Dict[Literal['foo', 'bar'], int]', got 'Dict[str, int]' instead

如何在列表中正确使用文字类型或作为字典键?

标签: pythonpycharmmypy

解决方案


推荐阅读