首页 > 解决方案 > 在python中输入带有嵌套元组的元组列表

问题描述

我正在尝试输入以下提示:

from typing import *

x = [('a',), (('b',), ('c', 'd'))]

f( k : list[ tuple[str] | tuple[str, tuple[str]]]):
    print(k)

并且不确定如何为此列表键入提示。

标签: pythontype-hintingmypytyping

解决方案


鉴于您的示例,递归数据类型的正确注释将需要前向引用,如下所示:

Tstr = tuple[str, ...] | tuple['Tstr', 'Tstr'] 

这意味着 anTstr要么是可变参数元组,要么是在每个坐标上str包含 a 的嵌套元组。Tstr

示例居民将是

('b',)                           # B1: base case with 1 element -- tuple[str] 
('c', 'd')                       # B2: base case with 2 elements -- tuple[str, str]
(('b',), ('c', 'd'))             # inductive case of tuple[B1, B2]
(('c', 'd'), ('b',))             # inductive case of tuple[B2, B1]
((('b',), ('c', 'd')), ('b',))   # inductive case of tuple[tuple[B2, B1], B1]
...

等等

list[Tstr]然后是一个非常好的类型提示(如果它的目的只是提示),但它不会通过 mypy 的类型检查(参见这个问题)。

如果您希望任何可用的python 类型检查器不抱怨,您需要满足于简化版本,即为归纳设置上限并明确指定允许的变体(例如Tstr = tuple[str, ...] | tuple[tuple[str, ...], tuple[str, ...]])。


推荐阅读