Python Strict Interfaces
Installation
pip install strict-interfacesDesign Goals
- Be as strict as possible
- Fail on import time
- Do not mess with
objectand/ortypeinheritance - Possibility to integrate in CPython Core
- Ability to use "out of the box" regardless support in an interpreter
Features
- Special keyword
implementson the class definition - Multiple interface implementation
- Implicit interface implementation
- Interface inheritance with overloading being restricted
- Special
isimplementationfunction similar toissubclass - Partial
issubclasssupport (see below) - It's restricted to create an interface instance
- It's restricted to inherit from
objectandinterfaceat the same time
Usage
Explicit implementation
class TestInterface(interfaces.interface):
def method(self, arg: typeT1) -> typeT2:
pass
class TestClass(interfaces.object, implements=[TestInterface]):
def method(self, arg: typeT1) -> typeT2:
passRaises when is not implemented
class TestInterface(interfaces.interface):
def method(self, arg):
pass
class TestClass(interfaces.object, implements=[TestInterface]):
passImplicit implementation and run-time check
class TestInterfaceA(interfaces.interface):
def method_a(arg: typeT1) -> typeT1:
pass
class TestInterfaceB(interfaces.interface):
def method_b(arg: typeT2) -> typeT2:
pass
class TestClass:
def method_a(arg: typeT1) -> typeT1:
pass
def method_b(arg: typeT2) -> typeT2:
pass
assert interfaces.isimplementation(TestClass, (TestInterfaceA, TestInterfaceB))isimplementation checks whether all interfaces are implemented
class TestInterfaceA(interfaces.interface):
def method_a(arg: typeT1) -> typeT1:
pass
class TestInterfaceB(interfaces.interface):
def method_b(arg: typeT2) -> typeT2:
pass
class TestClass:
def method_a(arg: typeT1) -> typeT1:
pass
# NOTE: In this case `isimplementation` behaves different than `issubclass`
assert not interfaces.isimplementation(TestClass, (TestInterfaceA, TestInterfaceB))
assert issubclass(TestClass, (TestInterfaceA, TestInterfaceB))Contributing
Pull requests, feature requests, and bug reports are always welcome!
github.com/lig/python-interfaces
Discussions
There are threads on Python Ideas mailing list and on Reddit.