Skip to content

Harden the checks of the implementations of abstract classes #598

Description

@tramora

Description

We noticed that the checks for correct implementations of abstract classes are a bit lax.
An error is raised if an abstract method is effectively implemented in the child class but no check is done against the actual parameters

Questions/Ideas

@popescu-v proposed this snippet to check both the method and its exact parameters

from abc import ABC, abstractmethod

class MyBase(ABC):

    @abstractmethod
    def my_method(self, a: int, b: int) -> None:
        pass

    @classmethod
    def __subclasshook__(cls, subclass):
        if cls is MyBase:
            if 'my_method' in subclass.__dict__:
                method = subclass.__dict__['my_method']
                # Check if the method has the correct number of parameters
                if method.__code__.co_argcount == 3:  # 2 parameters + self
                    return True
            return False
        return NotImplemented

class ValidSubclass(MyBase):
    def my_method(self, a: int, b: int) -> None:
        pass

class InvalidSubclass(MyBase):
    def my_method(self, a: int) -> None:  # Incorrect number of parameters
        pass

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Fields

    No fields configured for DevChore.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions