The Python standard library abc
(Abstract Base Class) module is often used to define and verify interfaces.
interface
differs from Python's abc
module in two important ways:
- Interface requirements are checked at class creation time, rather than at instance creation time. This means that
interface
can tell you if a class fails to implement an interface even if you never create any instances of that class. interface
requires that method signatures of implementations are compatible with signatures declared in interfaces. For example, the following code usingabc
does not produce an error:>>> from abc import ABCMeta, abstractmethod >>> class Base(metaclass=ABCMeta): ... ... @abstractmethod ... def method(self, a, b): ... pass ... >>> class Implementation(MyABC): ... ... def method(self): # Missing a and b parameters. ... return "This shouldn't work." ... >>> impl = Implementation() >>>
The equivalent code using
interface
produces an error telling us that the implementation method doesn't match the interface:>>> from interface import implements, Interface >>> class I(Interface): ... def method(self, a, b): ... pass ... >>> class C(implements(I)): ... def method(self): ... return "This shouldn't work" ... TypeError: class C failed to implement interface I: The following methods were implemented but had invalid signatures: - method(self) != method(self, a, b)