4

How do I test for subtypes in both Python 2 and Python 3?

In Python 2.7.18:

>>> import typing
>>> type_ = typing.List[str]
>>> issubclass(type_, typing.List)
True

But in Python 3.9.10, I get:

TypeError: Subscripted generics cannot be used with class and instance checks

The following works in my case but it is a hack! It would be better to see a more robust implementation as a builtin function in a future version of Python.

def _issubtype(type_, typeinfo):
    """
    Python 3 workaround for:
    TypeError: Subscripted generics cannot be used with class and instance checks

    Does not deal with typing.Union and probably numerous other corner cases.
    >>> _issubtype(typing.List[str], typing.List)
    True
    >>> _issubtype(typing.Dict[str, str], typing.List)
    False
    """
    try:  # Python 2
        return issubclass(type_, typeinfo)
    except TypeError:  # Python 3: "typing.List[str]".startswith("typing.List")
        return repr(type_).startswith(repr(typeinfo))
cclauss
  • 552
  • 6
  • 17

0 Answers0