Skip to content

Fix issubclass() to narrow down types of type variables #7930

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Nov 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 34 additions & 24 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3733,30 +3733,7 @@ def find_isinstance_check_helper(self, node: Expression) -> Tuple[TypeMap, TypeM
return {}, {}
expr = node.args[0]
if literal(expr) == LITERAL_TYPE:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would keep the above two lines in this function. To make the refactoring more 1-to-1.

vartype = get_proper_type(type_map[expr])
type = get_isinstance_type(node.args[1], type_map)
if isinstance(vartype, UnionType):
union_list = []
for t in get_proper_types(vartype.items):
if isinstance(t, TypeType):
union_list.append(t.item)
else:
# This is an error that should be reported earlier
# if we reach here, we refuse to do any type inference.
return {}, {}
vartype = UnionType(union_list)
elif isinstance(vartype, TypeType):
vartype = vartype.item
elif (isinstance(vartype, Instance) and
vartype.type.fullname == 'builtins.type'):
vartype = self.named_type('builtins.object')
else:
# Any other object whose type we don't know precisely
# for example, Any or a custom metaclass.
return {}, {} # unknown type
yes_map, no_map = conditional_type_map(expr, vartype, type)
yes_map, no_map = map(convert_to_typetype, (yes_map, no_map))
return yes_map, no_map
return self.infer_issubclass_maps(node, expr, type_map)
elif refers_to_fullname(node.callee, 'builtins.callable'):
if len(node.args) != 1: # the error will be reported elsewhere
return {}, {}
Expand Down Expand Up @@ -4367,6 +4344,39 @@ def push_type_map(self, type_map: 'TypeMap') -> None:
for expr, type in type_map.items():
self.binder.put(expr, type)

def infer_issubclass_maps(self, node: CallExpr,
expr: Expression,
type_map: Dict[Expression, Type]
) -> Tuple[TypeMap, TypeMap]:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a short docstring for the new function.

"""Infer type restrictions for an expression in issubclass call."""
vartype = type_map[expr]
type = get_isinstance_type(node.args[1], type_map)
if isinstance(vartype, TypeVarType):
vartype = vartype.upper_bound
vartype = get_proper_type(vartype)
if isinstance(vartype, UnionType):
union_list = []
for t in get_proper_types(vartype.items):
if isinstance(t, TypeType):
union_list.append(t.item)
else:
# This is an error that should be reported earlier
# if we reach here, we refuse to do any type inference.
return {}, {}
vartype = UnionType(union_list)
elif isinstance(vartype, TypeType):
vartype = vartype.item
elif (isinstance(vartype, Instance) and
vartype.type.fullname == 'builtins.type'):
vartype = self.named_type('builtins.object')
else:
# Any other object whose type we don't know precisely
# for example, Any or a custom metaclass.
return {}, {} # unknown type
yes_map, no_map = conditional_type_map(expr, vartype, type)
yes_map, no_map = map(convert_to_typetype, (yes_map, no_map))
return yes_map, no_map


def conditional_type_map(expr: Expression,
current_type: Optional[Type],
Expand Down
33 changes: 33 additions & 0 deletions test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -6512,3 +6512,36 @@ def access_after_declaration(self) -> None:

reveal_type(x) # N: Revealed type is 'builtins.int'
x = x + 1

[case testIsSubClassNarrowDownTypesOfTypeVariables]
from typing import Type, TypeVar, Generic

class Base:
field: int = 42

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

TypeT1 = TypeVar("TypeT1", bound=Type[Base])

class C1:
def method(self, other: type) -> int:
if issubclass(other, Base):
reveal_type(other) # N: Revealed type is 'Type[__main__.Base]'
return other.field
return 0

class C2(Generic[TypeT]):
def method(self, other: TypeT) -> int:
if issubclass(other, Base):
reveal_type(other) # N: Revealed type is 'Type[__main__.Base]'
return other.field
return 0

class C3(Generic[TypeT1]):
def method(self, other: TypeT1) -> int:
if issubclass(other, Base):
reveal_type(other) # N: Revealed type is 'TypeT1`1'
return other.field
return 0

[builtins fixtures/isinstancelist.pyi]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, now the two classes don't look the same, but you didn't do what I asked, I wanted type variables with different upper bounds, like Type[SomeClass], not just type.