2

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.

thorwhalen
  • 1,920
  • 14
  • 26
  • I think you are taking `isinstance` too literally. Just because `type(dict()) != Mapping` does not mean an instance of `dict` is not an instance of `Mapping`. – chepner Jan 28 '22 at 01:34

1 Answers1

0

The typing module has a few useful functions. You can access the contents of a subscripted generic like Union or Optional using get_args. This also works for subscripted type aliases such as List, Mapping, etc.

rspeed
  • 1,612
  • 17
  • 21