Last active
December 27, 2017 04:49
-
-
Save ianhoffman/e25899e8fca3c1ef8772f331b14031d0 to your computer and use it in GitHub Desktop.
The generic function pattern implemented for methods
This file contains 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
from functools import singledispatch | |
class singledispatchmethod(object): | |
def __init__(self, method): | |
self.method = singledispatch(method) | |
def register(self, klass, method=None): | |
return self.method.register(klass, func=method) | |
def __get__(self, instance=None, owner=None): | |
if instance or owner: | |
def _method(*args, **kwargs): | |
method = self.method.dispatch(args[0].__class__) | |
return method.__get__(instance, owner)(*args, **kwargs) | |
_method.__isabstractmethod__ = self.__isabstractmethod__ | |
_method.register = self.register | |
return _method | |
else: | |
return self | |
@property | |
def __isabstractmethod__(self): | |
return getattr(self.method, '__isabstractmethod__', False) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment