Interfaces for Python

8.2 · active · verified Sat Mar 28

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

Install

Imports

Quickstart

Define an interface by inheriting from `zope.interface.Interface`. Declare attributes using `zope.interface.Attribute` and methods with a standard Python function signature (without `self`). Implement the interface in a class using the `@implementer` decorator. Runtime verification can be done with `zope.interface.verify.verifyObject` to ensure adherence to the interface contract.

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"))

view raw JSON →