faif / python-patterns

A collection of design patterns/idioms in Python
40.21k stars 6.93k forks source link

ABC based interface in mvc pattern #331

Closed rednafi closed 4 years ago

rednafi commented 4 years ago

Defining interfaces in the following manner isn't very Pythonic:

class Interface:
    def method(self):
        raise NotImplementedError

Because this will still let you initialize the interface. The above example will only raise an error when you try to access the method which goes against the very definition of interfaces. You shouldn't be able to initialize an interface at all and it should fail early when you try to do so without subclassing. Python doc recommends using the abc module to define interfaces in the following manner:

from abc import ABC, abstractmethod

class Interface(ABC):
    @abstractmethod
    def method(self):
        pass

This will fail the moment you try to initialize the interface without subclassing. Changed that.