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.

1
  • 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. Commented Jan 28, 2022 at 1:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.