Skip to content

issubclass() doesn't narrow down types of type variables #7920

Closed

Description

@ambv

Example:

from typing import *

TypeT = TypeVar("TypeT", bound=type)

class Base:
    field: str = "Hey"

class C1:
    def method(self, other: type) -> str:
        if issubclass(other, Base):
            # reveal_type(other) == Type[Base]
            return other.field
        return "Hi"

class C2(Generic[TypeT]):
    def method(self, other: TypeT) -> str:
        if issubclass(other, Base):
            # reveal_type(other) == TypeT`1
            return other.field  # mypy error: "TypeT" has no attribute "field"
        return "Hi"

Actual behavior as of 0.740 included in the comments above. Expected behavior would be to not raise an error on the penultimate line.

Activity

  1. ilevkivskyi commented on Nov 11, 2019

    @ilevkivskyi
    Member

    Looks like an issue in checker.py (the logic around issubclass() is pretty ad-hoc there). One needs to add an elif for type variables in find_isinstance_check() there.

    This might potentially need also an adjustment in meet.py either in narrow_declared_type() or in is_overlapping_types() or in meet_types().

  2. TH3CHARLie commented on Nov 11, 2019

    @TH3CHARLie
    Collaborator

    @ilevkivskyi I'd like to take this

  3. ilevkivskyi commented on Nov 11, 2019

    @ilevkivskyi
    Member

    I'd like to take this

    OK, go ahead.

  4. added a commit that references this issue on Nov 14, 2019
    15280bf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions