是否有一个 Python 类型类表示“集合、列表或元组”之类的东西?

Sas*_*lla 5 python collections type-hinting

是否有一个 Pythontyping类用于不是映射的项目集合——即集合、列表或元组,但不是字典?即,这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
Run Code Online (Sandbox Code Playgroud)

Collection当然看起来很有希望,但听写也Collection很不错。

Gri*_*mar 3

为什么不简单地使用:

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'})
Run Code Online (Sandbox Code Playgroud)

结果:

True
True
True
False
Run Code Online (Sandbox Code Playgroud)

并且 的键入typed_f是典型用法,因此这会在一个好的 IDE 中向您发出警告:

typed_f({1: 'a', 2: 'b'})
Run Code Online (Sandbox Code Playgroud)