Skip to content

Instantly share code, notes, and snippets.

@jbweston
Last active March 15, 2018 09:31
Show Gist options
  • Save jbweston/90d722b46442b39a241596e755c152ad to your computer and use it in GitHub Desktop.
Save jbweston/90d722b46442b39a241596e755c152ad to your computer and use it in GitHub Desktop.
Abstract Interfaces in Python
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