带有字符串的类型提示列表和 mypy 中的字符串列表
Typehint list with strings and lists of strings in 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'])
A List[Union[str, List[str]]]
是“可以是字符串或字符串列表的项目列表”。
一种类型如何提示以下内容:
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'])
A List[Union[str, List[str]]]
是“可以是字符串或字符串列表的项目列表”。