首页 > 解决方案 > 在 mypy 中键入带有字符串和字符串列表的提示列表

问题描述

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

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

wherex是一个包含字符串的列表和字符串列表。

例如:

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

标签: pythontype-hintingmypy

解决方案


你想要的类型是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'])

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


推荐阅读