API Reference¶
-
class
interface.
Interface
[source]¶ Base class for interface definitions.
An interface defines a set of methods and/or attributes that should be provided by one or more classes, which are called “implementations” of the interface.
Classes can declare that they implement an interface
I
by subclassingimplements(I)
. During class construction, the base class generated byimplements(I)
will verify that the new class correctly implements all the methods required byI
.Interfaces cannot be instantiated.
Examples
Defining an Interface:
class KeyValueStore(Interface): def get(self, key): pass def set(self, key, value): pass def delete(self, key): pass
Implementing an Interface:
class InMemoryKeyValueStore(implements(KeyValueStore)): def __init__(self): self.data = {} def get(self, key): return self.data[key] def set(self, key, value): self.data[key] = value def delete(self, key): del self.data[key]
See also
-
classmethod
from_class
(existing_class, subset=None, name=None)[source]¶ Create an interface from an existing class.
Parameters: - existing_class (type) – The type from which to extract an interface.
- subset (list[str], optional) – List of methods that should be included in the interface. Default is to use all attributes not defined in an empty class.
- name (str, optional) – Name of the generated interface.
Default is
existing_class.__name__ + 'Interface'
.
Returns: interface – A new interface class with stubs generated from
existing_class
.Return type:
-
classmethod
-
interface.
implements
(*interfaces)¶ Make a base for a class that implements one or more interfaces.
Parameters: *interfaces (tuple) – One or more subclasses of Interface
.Returns: base – A type validating that subclasses must implement all interface methods of types in interfaces
.Return type: type Examples
Implementing an Interface:
class MyInterface(Interface): def method1(self, x): pass def method2(self, y): pass class MyImplementation(implements(MyInterface)): def method1(self, x): return x + 1 def method2(self, y): return y * 2
Implementing Multiple Interfaces:
class I1(Interface): def method1(self, x): pass class I2(Interface): def method2(self, y): pass class ImplBoth(implements(I1, I2)): def method1(self, x): return x + 1 def method2(self, y): return y * 2