1

Code:

import abc


class Interface(abc.ABC):
    @abc.abstractmethod
    @classmethod
    def make(cls): ...

class AObject(Interface):
    def __init__(self, a: int):
        self.a = a

    @classmethod
    def make(cls):
        return cls(a=3)

class BObject(Interface):
    def __init__(self, b: int):
        self.b = b

    @classmethod
    def make(cls):
        return cls(b=3)


data: tuple[Interface, ...] = (AObject, BObject) # Incompatible types in assignment (expression has type "Tuple[Type[AObject], Type[BObject]]", variable has type "Tuple[Interface, ...]")  [assignment]

There is an interface that implements classes and we need to specify that the classmethod make exists for the class. But if you specify the type tuple[Interface, ...], MyPy will return an error, because you can specify the type only for class instances, and not for the classes themselves

So, the question is — how to do it correctly?

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
Levik
  • 13
  • 3

1 Answers1

2

I'm not sure I understand your problem, but if you want to specify that a variable stores a class of some sort you can use typing.Type:

import abc
from typing import Tuple, Type
...
data: Tuple[Type[Interface], Type[Interface]] = (AObject, BObject)  # mypy is happy
Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
qouify
  • 3,698
  • 2
  • 15
  • 26