Reputation: 3130
Is there a Python typing
class for a collection of items that is not a mapping -- i.e., a set, list, or tuple, but not a dict? I.e., does this Unicorn
exist?
>>> 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
sure looked promising but dicts are Collection
s too.
Upvotes: 5
Views: 7205
Reputation: 9427
No, not that I know of.
This helper function I wrote a while ago may help you though, depending on what your goal is;
def is_iterable(item):
return hasattr(item, "__iter__") and not isinstance(item, dict)
You can easily add further exceptions in the isinstance call if required.
Upvotes: 2
Reputation: 31329
Why not simply use:
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'})
Result:
True
True
True
False
And the typing of typed_f
is typical usage, so this would get you a warning in a good IDE:
typed_f({1: 'a', 2: 'b'})
Upvotes: 3