Skip to main content

Go-style interfaces for Python

Project description

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pygopher_interfaces-0.1.3.tar.gz (8.5 kB view hashes)

Uploaded Source

Built Distribution

pygopher_interfaces-0.1.3-py3-none-any.whl (4.0 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page