Python 3: TypeError: Subscripted generics cannot be used with class and instance checks
Asked Answered
P

0

7

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))
Portulaca answered 23/1, 2022 at 18:36 Comment(2)
I head the same issue, upgrading to python 3.10.x solved my problem.Loon
How can I implement this workaround?Cecum

© 2022 - 2024 — McMap. All rights reserved.