Skip to content

Patch subtyping for metaclasses #2837

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 3 commits into from
Feb 11, 2017
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
17 changes: 12 additions & 5 deletions mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,11 @@ def visit_instance(self, left: Instance) -> bool:
return all(self.check_type_parameter(lefta, righta, tvar.variance)
for lefta, righta, tvar in
zip(t.args, right.args, right.type.defn.type_vars))
if isinstance(right, TypeType):
item = right.item
if isinstance(item, TupleType):
item = item.fallback
return isinstance(item, Instance) and is_subtype(left, item.type.metaclass_type)
else:
return False

Expand Down Expand Up @@ -269,11 +274,13 @@ def visit_type_type(self, left: TypeType) -> bool:
if isinstance(right, CallableType):
# This is unsound, we don't check the __init__ signature.
return right.is_type_obj() and is_subtype(left.item, right.ret_type)
if (isinstance(right, Instance) and
right.type.fullname() in ('builtins.type', 'builtins.object')):
# Treat builtins.type the same as Type[Any];
# treat builtins.object the same as Any.
return True
if isinstance(right, Instance):
if right.type.fullname() in ('builtins.type', 'builtins.object'):
# Treat builtins.type the same as Type[Any];
# treat builtins.object the same as Any.
return True
item = left.item
return isinstance(item, Instance) and is_subtype(item, right.type.metaclass_type)
return False


Expand Down
12 changes: 12 additions & 0 deletions test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -2845,3 +2845,15 @@ class Concrete(metaclass=Meta):

reveal_type(Concrete + X()) # E: Revealed type is 'builtins.str'
Concrete + "hello" # E: Unsupported operand types for + ("Meta" and "str")

[case testMetaclassSelftype]
from typing import TypeVar, Type

class M(type): pass
T = TypeVar('T', bound='A')

class M1(M):
def foo(cls: Type[T]) -> T: ...

class A(metaclass=M1): pass
reveal_type(A.foo()) # E: Revealed type is '__main__.A*'