Skip to content

Instantly share code, notes, and snippets.

@ianhoffman
Last active December 27, 2017 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianhoffman/e25899e8fca3c1ef8772f331b14031d0 to your computer and use it in GitHub Desktop.
Save ianhoffman/e25899e8fca3c1ef8772f331b14031d0 to your computer and use it in GitHub Desktop.
The generic function pattern implemented for methods
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