Interfaces for Python
Interfaces are objects that specify (document) the external behavior of objects that 'provide' them. An interface specifies behavior through informal documentation, attribute definitions, and invariants. `zope.interface` provides an implementation of 'object interfaces' for Python, facilitating Design By Contract. It is currently at version 8.2 (as of January 9, 2026) and is actively maintained by the Zope Toolkit project.
Warnings
- breaking The `implements` class-level function (e.g., `implements(IInterface)`) was removed in `zope.interface` version 6.0. It must be replaced by the `@zope.interface.implementer(IInterface)` class decorator.
- breaking `zope.interface` frequently drops support for older Python versions. Version 8.0 dropped Python 3.8, and 8.1 dropped Python 3.9. Ensure your Python environment meets the `requires_python` specification (>=3.10 for 8.2).
- breaking Starting with `zope.interface` 8.0, `pkg_resources` namespace packages were replaced by PEP 420 native namespace packages. This may affect package discovery, especially in older build systems or environments relying on `pkg_resources`.
- gotcha When defining methods in an `Interface`, omit the `self` argument from the signature. Interfaces describe how a method is *called*, not how it's implemented in a class. This is a common point of confusion.
- breaking For Python 3.14 and later, `zope.interface.common.builtins.IByteString` and `zope.interface.common.collections.IByteString` are no longer available from `zope.interface` version 7.2 onwards due to the removal of `collections.abc.ByteString` in Python 3.14.
- gotcha In `zope.interface` 5.0.0, internal singleton objects returned by APIs like `implementedBy` and `directlyProvidedBy` were made immutable. While this fixed potential 'pathological corner cases,' it might subtly affect highly unusual code that previously mutated these objects.
Install
-
pip install zope.interface
Imports
- Interface
from zope.interface import Interface
- Attribute
from zope.interface import Attribute
- implementer
from zope.interface import implementer
- verify
from zope.interface import verify
Quickstart
from zope.interface import Interface, Attribute, implementer, verify
class IGreeter(Interface):
"""An interface for objects that can greet."""
name = Attribute("The name of the greeter")
def greet(message: str) -> str:
"""Returns a greeting message."""
@implementer(IGreeter)
class HelloGreeter:
def __init__(self, name: str):
self.name = name
def greet(self, message: str) -> str:
return f"Hello, {message} from {self.name}!"
# Instantiate the implementing class
greeter_instance = HelloGreeter("World")
# Verify that the instance provides the interface
verify.verifyObject(IGreeter, greeter_instance)
# Use the object as per the interface
print(greeter_instance.greet("Python"))