Pythonic Interface definitions
interface provides facilities for declaring interfaces and for statically asserting that classes implement those interfaces. It supports Python 2.7 and Python 3.4+.
interface improves on Python’s abc module in two 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 meet the requirements of an interface even if you never create any instances of that class.
interface requires that method signatures of interface implementations are compatible with the signatures declared in the interface. For example, the following code using abc 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): ... return "This shouldn't work." ... >>> impl = Implementation() >>>
The equivalent code using interface produces an error indicating that the signature of our implementation method is incompatible with the signature of our interface declaration:
>>> 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)
Defining an Interface
To define an interface, simply subclass from interface.Interface and define method stubs in your class body.
from interface import Interface class MyInterface(Interface): def method1(self): pass def method2(self, arg1, arg2): pass
Implementing an Interface
To declare that a particular class implements an interface I, pass implements(I) as a base class for your class.
from interface import implements class MyClass(implements(MyInterface)): def method1(self): return "method1" def method2(self, arg1, arg2): return "method2"
$ pip install python-interface
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|Filename, Size & Hash SHA256 Hash Help||File Type||Python Version||Upload Date|
(18.9 kB) Copy SHA256 Hash SHA256
|Wheel||3.5||Dec 6, 2017|
(13.0 kB) Copy SHA256 Hash SHA256
|Source||None||Dec 6, 2017|