python - 在 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']
解决方案
你想要的类型是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]]]
是“可以是字符串或字符串列表的项目列表”。
推荐阅读
- django - django搜索返回一个空白页
- ios - iOS - WKURLSchemeHandler 未在自定义方案上调用
- python - 使用模板中的表单从购物车中删除在 Django 中不起作用
- reactjs - React Query useInfiniteQuery 使单个项目无效
- powerbi - 基于列过滤 PowerBI 度量
- django - Django-apps.py 无法识别
- javascript - 数组之和 - JS
- html - 为什么我的 Bootstrap [4.2] 导航栏切换器不工作?
- pine-script - 坚持交易视图策略
- visual-studio - 创建引用引用的 .dll 而不使用 .nuspec 的 nuget 包