Skip to content

Bug: issubclass() doesn't narrow TypeVar type with Protocol #8556

Description

@antonagestam

Using issubclass with a runtime checkable Protocol and a union-bound TypeVar fails to narrow the type. The below example is from invoking mypy with mypy --python-version=3.8 reproduce-issubclass-bug.py. The issue seems similar to #7920. Tested on both 0.770 and master (0.770+dev.afe0667bbe85e048b6bb4e3fc1b7d5a375b7d01f).

fromtypingimportAnyfromtypingimportProtocolfromtypingimportruntime_checkablefromtypingimportTypefromtypingimportTypeVarfromtypingimportUnionT=TypeVar("T", bound=Any)
@runtime_checkableclassParsable(Protocol):
@classmethoddefparse(cls: Type[T], data: Any) ->T:
...
R=TypeVar("R", bound=Union[Parsable, str])
defparse_object(response_type: Type[R], item: Any) ->R:
ifissubclass(response_type, Parsable):
# note: Revealed type is 'Type[reproduce-issubclass-bug.Parsable]'reveal_type(response_type)
# error: Incompatible return value type (got "Parsable", expected "R")returnresponse_type.parse(item)
# note: Revealed type is 'Type[R`-1]'reveal_type(response_type)
# error: Too many arguments for "Parsable"# error: Incompatible return value type (got "Union[Parsable, str]", expected "R")returnresponse_type(item)

Output:

reproduce-issubclass-bug.py:25: note: Revealed type is 'Type[reproduce-issubclass-bug.Parsable]'
reproduce-issubclass-bug.py:27: error: Incompatible return value type (got "Parsable", expected "R")
reproduce-issubclass-bug.py:29: note: Revealed type is 'Type[R`-1]'
reproduce-issubclass-bug.py:32: error: Too many arguments for "Parsable"
reproduce-issubclass-bug.py:32: error: Incompatible return value type (got "Union[Parsable, str]", expected "R")
Found 3 errors in 1 file (checked 1 source file)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions