Python's typing
module allows containers of specific object types to be described, such as Sequence[numbers.Real]
. However, the container interfaces in collections.abc
do not accept such parameters, so I can only check isinstance(value, abc.Sequence)
. Is there any directway to check if isinstance(value, Sequence[numbers.Real])
(without using loops/comprehensions etc)
Asked
Active
Viewed 260 times
0

Martijn Pieters
- 1,048,767
- 296
- 4,058
- 3,343

blue_note
- 27,712
- 9
- 72
- 90
-
1The type hinting is aimed at specialist type-checking tools such as `mypy`, not at run-time checking. As such, `isinstance()` is not really supported for generic types. – Martijn Pieters Dec 11 '16 at 12:46
-
Thanks for the answer. Still, if a need my code to behave differently for a list of `X`s than for a list of `Y`s, what would be the suggested way of doing that? Do I have to use `all(isinstance(val, X) for val in seq)` or something like that, or is there some better way of doing it?? – blue_note Dec 11 '16 at 12:53
-
1Try not to write code that needs to check for types in the first place? – Martijn Pieters Dec 11 '16 at 12:54
-
1See if https://github.com/agronholm/typeguard can help. – Alex Hall Dec 11 '16 at 12:54
-
@MartijnPieters: despite the python mottos, not always possible. even the standard libraries themselves make heavy use of `isinstance` is some cases. – blue_note Dec 11 '16 at 12:59
-
don't try and enforce things (e.g all list elements *must* be of `X` type). Just accept the list and raise an appropriate error if the type doesn't match. – Dimitris Fasarakis Hilliard Dec 11 '16 at 13:35