Home > Software design >  mypy doesn't warn about instantiating pure virtual class
mypy doesn't warn about instantiating pure virtual class

Time:11-11

I have an abstract class that specifies a pure virtual method run:

class Father:
    def __init__(self):
        self.i = 800
    def run(self, s: str) -> int:
        pass

class Son(Father):
    def walk(self, i: int) -> int:
        return self.i i 800

s = Son()

When I run mypy no warnings are issued, why?

CodePudding user response:

Your example doesn't have an abstract class or a pure virtual method (which, strictly speaking, isn't a thing in Python; it'd just be an abstract method). It has two standard classes in a hierarchy, and the run function is a regular function.

If you want an abstract method, you'll have to mark it as such using the bits and bobs in the abc module.

from abc import ABC, abstractmethod


class Father(ABC):
    def __init__(self):
        self.i = 800

    @abstractmethod
    def run(self, s: str) -> int:
        ...


class Son(Father):
    def walk(self, i: int) -> int:
        return self.i   i   800


s = Son()

This results in

TypeError: Can't instantiate abstract class Son with abstract method run

at runtime and

error: Cannot instantiate abstract class "Son" with abstract attribute "run"

at mypy time.

If you don't care for the runtime check, don't derive Father from ABC.

  • Related