Python distinguish between abstract method and abstract attribute

Viewed 191

In python, is there a way to enforce attribute vs method with an abstract class?

For example if I want to enforce a method like the following:

Class AbstractCar(ABC):
  
  @abstractmethod
  def drive():
    pass

then this class would still be fine to instantiate.

Class Car(AbstractCar):
  drive = 5 # This satisfies the @abstractmethod above but is not a method

or vice versa with:

  @property
  @abstractmethod

1 Answers

If I were you I would start using a type checker such as mypy.

Whenever I write Python lately, I always try to keep it as safe as I can by using tools like flake8 and mypy for validations. Here's your code with some type-hints added:

test.py

from abc import ABC, abstractmethod


class AbstractCar(ABC):
    @abstractmethod
    def drive(self) -> None:
        pass


class Car(AbstractCar):
    drive = 5

And here is the warning for doing this type of override:

$ mypy test.py
mypy.py:10: error: Incompatible types in assignment (expression has type "int",
base class "AbstractCar" defined the type as "Callable[[AbstractCar], None]")
Found 1 error in 1 file (checked 1 source file)
Related