Last active
March 15, 2018 09:31
-
-
Save jbweston/90d722b46442b39a241596e755c152ad to your computer and use it in GitHub Desktop.
Abstract Interfaces in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import abc | |
class Interface(abc.ABC): | |
__slots__ = () | |
@classmethod | |
def __subclasshook__(cls, obj): | |
if cls is not Interface: | |
return NotImplemented | |
try: | |
return all(callable(getattr(obj, method) | |
for method in cls.__abstractmethods__) | |
except AttributeError: | |
return False | |
# Example | |
# Don't need to explicitly implement __subclasshook__ | |
class Iterator(Interface): | |
@abc.abstractmethod | |
def __iter__(self): | |
pass | |
@abc.abstractmethod | |
def next(self): | |
pass | |
it = iter(list()) # don't need to explicitly subclass | |
print(isinstance(it, Iterator)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment