Skip to content

Commit

Permalink
Do not support metaclasses not inheriting from type (#2820)
Browse files Browse the repository at this point in the history
Fix #2818.

ABCMeta requires special treatment.

Related: #2475
  • Loading branch information
elazarg authored and JukkaL committed Feb 7, 2017
1 parent b731899 commit 452a64f
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
2 changes: 1 addition & 1 deletion mypy/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2024,7 +2024,7 @@ def calculate_metaclass_type(self) -> 'Optional[mypy.types.Instance]':
return None

def is_metaclass(self) -> bool:
return self.has_base('builtins.type')
return self.has_base('builtins.type') or self.fullname() == 'abc.ABCMeta'

def _calculate_is_enum(self) -> bool:
"""
Expand Down
3 changes: 3 additions & 0 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -966,6 +966,9 @@ def analyze_metaclass(self, defn: ClassDef) -> None:
if not isinstance(sym.node, TypeInfo) or sym.node.tuple_type is not None:
self.fail("Invalid metaclass '%s'" % defn.metaclass, defn)
return
if not sym.node.is_metaclass():
self.fail("Metaclasses not inheriting from 'type' are not supported", defn)
return
inst = fill_typevars(sym.node)
assert isinstance(inst, Instance)
defn.info.declared_metaclass = inst
Expand Down
14 changes: 11 additions & 3 deletions test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -2770,9 +2770,9 @@ class B(A, metaclass=Y): pass # E: Inconsistent metaclass structure for 'B'
class M:
x = 0 # type: int

class A(metaclass=M): pass
class A(metaclass=M): pass # E: Metaclasses not inheriting from 'type' are not supported

reveal_type(A.x) # E: Revealed type is 'builtins.int'
A.x # E: "A" has no attribute "x"

[case testMetaclassTypeReveal]
from typing import Type
Expand All @@ -2785,6 +2785,14 @@ def f(TA: Type[A]):
reveal_type(TA) # E: Revealed type is 'Type[__main__.A]'
reveal_type(TA.x) # E: Revealed type is 'builtins.int'

[case testSubclassMetaclass]
class M1(type):
x = 0
class M2(M1): pass
class C(metaclass=M2):
pass
reveal_type(C.x) # E: Revealed type is 'builtins.int'

[case testMetaclassSubclass]
from typing import Type
class M(type):
Expand Down Expand Up @@ -2822,4 +2830,4 @@ from typing import Tuple
class M(Tuple[int]): pass
class C(metaclass=M): pass # E: Invalid metaclass 'M'

[builtins fixtures/tuple.pyi]
[builtins fixtures/tuple.pyi]

0 comments on commit 452a64f

Please sign in to comment.