2

The issue arises when code instantiates an instance of the supertype. Here's an example.

T = TypeVar("T")

class A(Generic[T], metaclass=abc.ABCMeta):
  
  @abc.abstractmethod
  def hello(self, arg: T):
    raise NotImplementedError

class B(A[float]):   

  def hello(self, arg: float):
    print("class B")

def make_an_a_subclass(clsname: Type[A]) -> A:
  return clsname() # error on this line

b = make_an_a_subclass(B) b.hello(1.0)

pytype returns an error, that I can't instantiate "clsname" because clsname is an instance of A, which is abstract:

Can't instantiate A with abstract methods hello [not-instantiable]

But I want make_an_a_subclass to accept a Type that is any subclass of A, but not A itself. Is there a way to annotate this?

Note, this has been made explicitly possible in mypy: https://github.com/python/mypy/pull/2853 Only seems to cause problems for pytype.

Carson McNeil
  • 790
  • 9
  • 22
  • I think this is an overkill. There's no way B can be provided with an instance of A since A is an abstract class and hence can't be instantiated. So you should never come across a situation where this will be needed unless you change A into a regular base class. But in that case this error will go away. – NotAName Feb 19 '21 at 02:46
  • Note, it does seem as if mypy explicitly allows this? https://github.com/python/mypy/pull/2853 – Carson McNeil Feb 19 '21 at 02:53
  • @pavel Why wouldn't this be needed? Perhaps there's some confusion? My function make_an_a_subclass accepts a Type[A] not an instance of A, it needs to instantiate it itself. True, there's no reason that make_an_a_subclass would ever receive "A" rather than a subclass, which is why I want pytype to not throw an error. – Carson McNeil Feb 19 '21 at 03:05
  • Yeah, sorry. I misunderstood the question a bit. – NotAName Feb 19 '21 at 03:20

0 Answers0