pygopher-interfaces

Go-style interfaces for Python

Status PyPI - Python Version PyPI - License Read the Docs Test Coverage Code Quality

Interfaces in the Go programming language are a bit different than those found in Java or C++, as they are implicit. This means that there is no explicit “implements” relationship between the interface definition and an implementation of the defined interface. A type implements an interface by implementing all of the methods defined. When we wish to define an interface in Python, we typically use abstract base classes to define them because we can enforce implementation of methods. This requires us to use inheritance, which couples the interface and the implementation.

This package emulates Go-style interfaces by creating an Interface metaclass that can be used to construct Python classes that override issubclass to test whether a class implements the methods of the interface class, rather than whether it inherits from the interface class.

This is a tiny package that emulates on of my favorite features of Go.

Installation

pip install pygopher-interfaces
# or:
# pipenv install pygopher-interfaces
# poetry add pygopher-interfaces

Usage

To create an interface class, use the Interface metaclass.

from pygopher.interfaces import Interface


class RepositoryInterface(metaclass=Interface):
    def get(account_id: int) -> Account:
        raise NotImplementedError

    def add(account: Account):
        raise NotImplementedError


class MysqlRepository:
    def get(account_id: int) -> Account:
        ...

    def add(account: Account):
        ...


>>> issubclass(MysqlRepository, RepositoryInterface)
True