簡體   English   中英

是否有一個 Python 鍵入 class 表示“集合、列表或元組”之類的東西?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM