带有字符串的类型提示列表和 mypy 中的字符串列表

问题描述

一种类型将如何提示以下内容

def f(x : <type>) -> None: print(x)

其中 x 是包含字符串的列表和字符串列表。

例如:

# example 1
['a','sdf',['sd','sdg'],'oidsf d','as',['asf','asr']]
# example 2
[['as','asfd'],['oei','afgdf'],'egt','aergaer']

解决方法

您想要的类型是Union

from typing import List,Union


def f(x: List[Union[str,List[str]]]) -> None:
    print(x)


f(['a','sdf',['sd','sdg'],'oidsf d','as',['asf','asr']])
f([['as','asfd'],['oei','afgdf'],'egt','aergaer'])

List[Union[str,List[str]]] 是“可以是字符串或字符串列表的项目列表”。