Metaclass usage example

Mypy supports the lookup of attributes in the metaclass:

  1. from typing import Type, TypeVar, ClassVar
  2. T = TypeVar('T')
  3.  
  4. class M(type):
  5. count: ClassVar[int] = 0
  6.  
  7. def make(cls: Type[T]) -> T:
  8. M.count += 1
  9. return cls()
  10.  
  11. class A(metaclass=M):
  12. pass
  13.  
  14. a: A = A.make() # make() is looked up at M; the result is an object of type A
  15. print(A.count)
  16.  
  17. class B(A):
  18. pass
  19.  
  20. b: B = B.make() # metaclasses are inherited
  21. print(B.count + " objects were created") # Error: Unsupported operand types for + ("int" and "str")