I'd love to be able to reuse typing
a lot more, namely for type checking, and preferably in a way that's consistent with the usual way to check if something is of the type of...
(My) ideal would be to be able to do something like:
from typing import Union, Iterable, Any, Mapping
KeysType = checkable(Union[Iterable[str], Mapping[str, Any]])
assert isinstance(['foo', 'bar'], KeysType)
assert not isinstance([3, 'foo', 'bar'], KeysType)
assert isinstance({'foo': 1, 'bar': 2}, KeysType)
assert isinstance({0: 0, 'foo': 1, 'bar': 2}, KeysType)
assert not isinstance(5, KeysType)
Of course, something is a bit off since I'm using isinstance
to mean has_interface_of
or has_compatible_stucture
. When wish bothers me, I tell myself this:
from collections.abc import Mapping
isinstance(dict(), Mapping)
Yet a dict
is not an instance of a Mapping
.
Still, even a custom is_sorta_like_this_type
function instead of the isinstance
function would do, if hooking into the behavior of isinstance
is too much of scary aberration.
Similar questions have been asked on stackoverflow, but none of the proposed answers are quite satisfactory to me -- though this one, though hacky, is the closest I got.