Jes*_*eke 4 type-hinting python-3.x
假设我有一个接受a Garthok,an Iterable[Garthok],an Iterable[Iterable[Garthok]]等的函数。
def narfle_the_garthoks(arg):
if isinstance(arg, Iterable):
for value in arg:
narfle(arg)
else:
arg.narfle()
Run Code Online (Sandbox Code Playgroud)
有什么方法可以为arg指定类型提示,以指示它接受Iterables中Garthoks的任何级别?我怀疑不是,但以为我会检查我是否缺少某些东西。
解决方法是,我仅指定几个级别,然后以结尾Iterable[Any]。
Union[Garthok,
Iterable[Union[Garthok,
Iterable[Union[Garthok,
Iterable[Union[Garthok, Iterable[Any]]]]]]]]
Run Code Online (Sandbox Code Playgroud)
您可以使用类型别名和正向引用字符串,在键入语言中指定递归类型,
Garthoks = Union[Garthok, Iterable['Garthoks']]
Run Code Online (Sandbox Code Playgroud)
请注意,mypy尚不支持递归类型。但最终可能会添加。
| 归档时间: |
|
| 查看次数: |
527 次 |
| 最近记录: |