{"id":19742036,"url":"https://github.com/ksindi/implements","last_synced_at":"2025-04-30T06:30:47.894Z","repository":{"id":54600873,"uuid":"91971749","full_name":"ksindi/implements","owner":"ksindi","description":":snake: Pythonic interfaces using decorators","archived":false,"fork":false,"pushed_at":"2023-11-04T02:37:15.000Z","size":80,"stargazers_count":34,"open_issues_count":0,"forks_count":4,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-04-26T10:38:58.883Z","etag":null,"topics":["interfaces","oop","python"],"latest_commit_sha":null,"homepage":"http://implements.readthedocs.io/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ksindi.png","metadata":{"files":{"readme":"README.rst","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-05-21T16:33:40.000Z","updated_at":"2024-10-31T08:35:37.000Z","dependencies_parsed_at":"2024-11-12T01:31:10.549Z","dependency_job_id":"078a948a-c7a6-4ec9-a58d-165fd2a8b929","html_url":"https://github.com/ksindi/implements","commit_stats":null,"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ksindi%2Fimplements","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ksindi%2Fimplements/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ksindi%2Fimplements/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ksindi%2Fimplements/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ksindi","download_url":"https://codeload.github.com/ksindi/implements/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251653964,"owners_count":21622229,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["interfaces","oop","python"],"created_at":"2024-11-12T01:28:51.032Z","updated_at":"2025-04-30T06:30:47.637Z","avatar_url":"https://github.com/ksindi.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"Implements\n==========\n\n.. image:: https://travis-ci.org/ksindi/implements.svg?branch=master\n    :target: https://travis-ci.org/ksindi/ksindi/implements\n    :alt: Build Status\n.. image:: https://img.shields.io/pypi/v/implements.svg\n    :target: https://pypi.python.org/pypi/implements\n    :alt: PyPI Version\n\n*Pythonic interfaces using decorators*\n\nDecorate your implementation class with `@implements(\u003cInterfaceClass\u003e)`.\nThat's it! `implements` will ensure that your implementation satisfies\nattributes, methods and their signatures as defined in your interface.\n\nMoreover, interfaces are enforced via composition. Implementations\ndon't inherit interfaces. Your MROs remain untouched and interfaces\nare evaluated early during import instead of class instantiation.\n\nInstall\n-------\n\nImplements is available on PyPI and can be installed with `pip \u003chttps://pip.pypa.io\u003e`_::\n\n    pip install implements\n\nNote Python 3.6+ is required as it relies on new features of `inspect` module.\n\nAdvantages\n----------\n\n1. `Favor composition over inheritance \u003chttps://en.wikipedia.org/wiki/Composition_over_inheritance\u003e`_.\n\n2. 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.\n\n3. 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.\n\n4. It's cleaner. Using decorators makes it clear we want shared behavior. Also, arguments are not allowed to be renamed.\n\nUsage\n-----\n\nWith 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.\n\n\n.. code-block:: python\n\n    from implements import Interface, implements\n\n\n    class Duck:\n        def __init__(self, age):\n            self.age = age\n\n\n    class Flyable(Interface):\n        @staticmethod\n        def migrate(direction):\n            pass\n\n        def fly(self) -\u003e str:\n            pass\n\n\n    class Quackable(Interface):\n        def fly(self) -\u003e bool:\n            pass\n\n        def quack(self):\n            pass\n\n\n    @implements(Flyable)\n    @implements(Quackable)\n    class MallardDuck(Duck):\n        def __init__(self, age):\n            super(MallardDuck, self).__init__(age)\n\n        def migrate(self, dir):\n            return True\n\n        def fly(self):\n            pass\n\n\nThe above would throw the following errors:\n\n.. code-block:: python\n\n    NotImplementedError: 'MallardDuck' must implement method 'fly((self) -\u003e bool)' defined in interface 'Quackable'\n    NotImplementedError: 'MallardDuck' must implement method 'quack((self))' defined in interface 'Quackable'\n    NotImplementedError: 'MallardDuck' must implement method 'migrate((direction))' defined in interface 'Flyable'\n\nYou can find a more detailed example in ``example.py`` and by looking at ``tests.py``.\n\nJustification\n-------------\n\nThere are currently two idiomatic ways to rewrite the above example.\n\nThe first way is to write base classes with mixins raising ``NotImplementedError`` in each method.\n\n.. code-block:: python\n\n    class Duck:\n        def __init__(self, age):\n            self.age = age\n\n\n    class Flyable:\n        @staticmethod\n        def migrate(direction):\n            raise NotImplementedError(\"Flyable is an abstract class\")\n\n        def fly(self) -\u003e str:\n            raise NotImplementedError(\"Flyable is an abstract class\")\n\n\n    class Quackable:\n        def fly(self) -\u003e bool:\n            raise NotImplementedError(\"Quackable is an abstract class\")\n\n        def quack(self):\n            raise NotImplementedError(\"Quackable is an abstract class\")\n\n\n    class MallardDuck(Duck, Quackable, Flyable):\n\n        def __init__(self, age):\n            super(MallardDuck, self).__init__(age)\n\n        def migrate(self, dir):\n            return True\n\n        def fly(self):\n            pass\n\nBut there are a couple drawbacks implementing it this way:\n\n1. We would only get a ``NotImplementedError`` when calling ``quack`` which can happen much later during runtime. Also, raising ``NotImplementedError`` everywhere looks clunky.\n\n2. It's unclear without checking each parent class where super is being called.\n\n3. 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 \u003chttps://www.python.org/download/releases/2.3/mro/\u003e`_.\n\n4. The writer of ``MallardDuck`` made method ``migrate`` an instance method and renamed the argument to ``dir`` which is confusing.\n\n5. We really want to be differentiating between behavior and inheritance.\n\nThe advantage of using implements is it looks cleaner and you would get errors at import time instead of when the method is actually called.\n\nAnother way is to use abstract base classes from the built-in ``abc`` module:\n\n.. code-block:: python\n\n    from abc import ABCMeta, abstractmethod, abstractstaticmethod\n\n\n    class Duck(metaclass=ABCMeta):\n        def __init__(self, age):\n            self.age = age\n\n\n    class Flyable(metaclass=ABCMeta):\n        @abstractstaticmethod\n        def migrate(direction):\n            pass\n\n        @abstractmethod\n        def fly(self) -\u003e str:\n            pass\n\n\n    class Quackable(metaclass=ABCMeta):\n        @abstractmethod\n        def fly(self) -\u003e bool:\n            pass\n\n        @abstractmethod\n        def quack(self):\n            pass\n\n\n    class MallardDuck(Duck, Quackable, Flyable):\n        def __init__(self, age):\n            super(MallardDuck, self).__init__(age)\n\n        def migrate(self, dir):\n            return True\n\n        def fly(self):\n            pass\n\n\nUsing abstract base classes has the advantage of throwing an error earlier\non instantiation if a method is not implemented; also, there are static analysis\ntools that warn if two methods have different signatures. But it doesn't solve\nissues 2-4 and implements will throw an error even earlier in import.\nIt also in my opinion doesn't look pythonic.\n\nCredit\n------\n\nImplementation was inspired by a `PR \u003chttps://github.com/pmatiello/python-interface/pull/1/files\u003e`_ of @elifiner.\n\nTest\n----\n\nRunning unit tests::\n\n    make test\n\nRunning linter::\n\n    make lint\n\nRunning tox::\n\n    make test-all\n\nLicense\n-------\n\nApache License v2\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fksindi%2Fimplements","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fksindi%2Fimplements","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fksindi%2Fimplements/lists"}