Skip to main content

Implements

Build Status PyPI Version

Pythonic interfaces using decorators

Decorate your implementation class with @implements(<InterfaceClass>). That’s it!. implements will ensure that your implementation satisfies attributes, methods and their signatures as defined in your interface.

Moreover, interfaces are enforced via composition. Implementations don’t inherit interfaces. Your MROs remain untouched and interfaces are evaluated early during import instead of class instantiation.

Install

Implements is available on PyPI and can be installed with pip:

pip install implements

Note Python 3.6+ is required as it relies on new features of inspect module.

Advantages

  1. Favor composition over inheritance.

  2. Inheriting from multiple classes can be problematic, especially when the superclasses have the same method name but different signatures. Implements will throw a descriptive error if that happens to ensure integrity of contracts.

  3. The decorators are evaluated at import time. Any errors will be raised then and not when an object is instantiated or a method is called.

  4. It’s cleaner. Using decorators makes it clear we want shared behavior. Also, arguments are not allowed to be renamed.

Usage

With _implements_, implementation classes and interface classes must have their own independent class hierarchies. Unlike common patterns, the implementation class must not inherit from an interface class. From version 0.3.0 and onwards, this condition is checked automatically and an error is raised on a violation.

from implements import Interface, implements


class Duck:
    def __init__(self, age):
        self.age = age


class Flyable(Interface):
    @staticmethod
    def migrate(direction):
        pass

    def fly(self) -> str:
        pass


class Quackable(Interface):
    def fly(self) -> bool:
        pass

    def quack(self):
        pass


@implements(Flyable)
@implements(Quackable)
class MallardDuck(Duck):
    def __init__(self, age):
        super(MallardDuck, self).__init__(age)

    def migrate(self, dir):
        return True

    def fly(self):
        pass

The above would throw the following errors:

NotImplementedError: 'MallardDuck' must implement method 'fly((self) -> bool)' defined in interface 'Quackable'
NotImplementedError: 'MallardDuck' must implement method 'quack((self))' defined in interface 'Quackable'
NotImplementedError: 'MallardDuck' must implement method 'migrate((direction))' defined in interface 'Flyable'

You can find a more detailed example in example.py and by looking at tests.py.

Justification

There are currently two idiomatic ways to rewrite the above example.

The first way is to write base classes with mixins raising NotImplementedError in each method.

class Duck:
    def __init__(self, age):
        self.age = age


class Flyable:
    @staticmethod
    def migrate(direction):
        raise NotImplementedError("Flyable is an abstract class")

    def fly(self) -> str:
        raise NotImplementedError("Flyable is an abstract class")


class Quackable:
    def fly(self) -> bool:
        raise NotImplementedError("Quackable is an abstract class")

    def quack(self):
        raise NotImplementedError("Quackable is an abstract class")


class MallardDuck(Duck, Quackable, Flyable):

    def __init__(self, age):
        super(MallardDuck, self).__init__(age)

    def migrate(self, dir):
        return True

    def fly(self):
        pass

But there are a couple drawbacks implementing it this way:

  1. We would only get a NotImplementedError when calling quack which can happen much later during runtime. Also, raising NotImplementedError everywhere looks clunky.

  2. It’s unclear without checking each parent class where super is being called.

  3. Similarly the return types of fly in Flyable and Quackable are different. Someone unfamiliar with Python would have to read up on Method Resolution Order.

  4. The writer of MallardDuck made method migrate an instance method and renamed the argument to dir which is confusing.

  5. We really want to be differentiating between behavior and inheritance.

The advantage of using implements is it looks cleaner and you would get errors at import time instead of when the method is actually called.

Another way is to use abstract base classes from the built-in abc module:

from abc import ABCMeta, abstractmethod, abstractstaticmethod


class Duck(metaclass=ABCMeta):
    def __init__(self, age):
        self.age = age


class Flyable(metaclass=ABCMeta):
    @abstractstaticmethod
    def migrate(direction):
        pass

    @abstractmethod
    def fly(self) -> str:
        pass


class Quackable(metaclass=ABCMeta):
    @abstractmethod
    def fly(self) -> bool:
        pass

    @abstractmethod
    def quack(self):
        pass


class MallardDuck(Duck, Quackable, Flyable):
    def __init__(self, age):
        super(MallardDuck, self).__init__(age)

    def migrate(self, dir):
        return True

    def fly(self):
        pass

Using abstract base classes has the advantage of throwing an error earlier on instantiation if a method is not implemented; also, there are static analysis tools that warn if two methods have different signatures. But it doesn’t solve issues 2-4 and implements will throw an error even earlier in import. It also in my opinion doesn’t look pythonic.

Credit

Implementation was inspired by a PR of @elifiner.

Test

Running unit tests:

make test

Running linter:

make lint

Running tox:

make test-all

License

Apache License v2

Metadata

Release files for implements 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for implements 0.3.0
File Size Uploaded Provenance Actions
implements-0.3.0.tar.gz 22.5 kB Without provenance Details for implements-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for implements 0.3.0
File Interpreter ABI Platform Actions
implements-0.3.0-py2.py3-none-any.whl Python 2, Python 3 none any Details for implements-0.3.0-py2.py3-none-any.whl

Total release size: 32.4 kB

Release files / implements-0.3.0.tar.gz

Download URL implements-0.3.0.tar.gz
Size 22.5 kB
Tags Source
SHA-256 checksum
How to use checksums
1e93cf9407f8af127724717376b8e16c2e8b5ce8afbe6b1f4bf113d02e124835
BLAKE2b-256 checksum
How to use checksums
12ccc8bd60029e8b9aefdbc6e7bd78051e28c2d5f04c40e1161f5c4f5df6ef2f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.3.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/44.0.0 requests-toolbelt/0.9.1 tqdm/4.47.0 CPython/3.8.3

Release files / implements-0.3.0-py2.py3-none-any.whl

Download URL implements-0.3.0-py2.py3-none-any.whl
Size 9.9 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
937be7f9183dc2f098e224b1ff7f9c2fdc76f9b622e46d72e481e57356eec959
BLAKE2b-256 checksum
How to use checksums
62c9fc0825d386ca1d90bd1ddb60a47769b3d6a39ffa00a61c1c0ac2415cb126
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.3.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/44.0.0 requests-toolbelt/0.9.1 tqdm/4.47.0 CPython/3.8.3

Security for implements 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page