[英]What is a suitable type (from the typing module) for list, tuple or set in Python
[英]Is there a Python typing class that means “set, list, or tuple”-like thing?
是否有一个 Python typing
class 用于不是映射的项目集合 - 即,集合,列表或元组,但不是字典? 即,这个Unicorn
存在吗?
>>> from typing import Unicorn
>>> isinstance({1, 2, 3}, Unicorn)
True
>>> isinstance([1, 2, 3], Unicorn)
True
>>> isinstance((1, 2, 3), Unicorn)
True
>>> isinstance({1: 'a', 2: 'b'}, Unicorn)
False
Collection
看起来很有希望,但 dicts 也是Collection
。
为什么不简单地使用:
from typing import List, Tuple, Set, Union
def test(x):
print(isinstance(x, (List, Tuple, Set)))
def typed_f(x: Union[List, Tuple, Set]):
print(x)
test({1, 2, 3})
test([1, 2, 3])
test((1, 2, 3))
test({1: 'a', 2: 'b'})
结果:
True
True
True
False
typed_f
的输入是典型的用法,所以这会给你一个好的 IDE 的警告:
typed_f({1: 'a', 2: 'b'})
不,不是我知道的。
我不久前写的这个助手 function 可能会对你有所帮助,这取决于你的目标是什么;
def is_iterable(item):
return hasattr(item, "__iter__") and not isinstance(item, dict)
如果需要,您可以轻松地在 isinstance 调用中添加更多例外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.