![](/img/trans.png)
[英]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.