Skip to content

Instantly share code, notes, and snippets.

@zaltoprofen
Created August 18, 2018 14:25
Show Gist options
  • Save zaltoprofen/047f3f58be75e9d50a2d5fcc0ea4cbfc to your computer and use it in GitHub Desktop.
Save zaltoprofen/047f3f58be75e9d50a2d5fcc0ea4cbfc to your computer and use it in GitHub Desktop.
from functools import singledispatch, wraps
class Foo(object):
@singledispatch
def foo(self, arg):
print('called original')
@foo.register(int)
def _(self, arg):
print('called dispatched')
f = Foo()
f.foo('hoge') # called original
f.foo(770) # called original
def methoddispatch(method):
method = singledispatch(method)
@wraps(method)
def over(self, *args, **kwargs):
return method.dispatch(type(args[0]))(self, *args, **kwargs)
over.__dict__ = method.__dict__
return over
class Bar(object):
@methoddispatch
def bar(self, arg):
print('called original')
@bar.register(int)
def _(self, arg):
print('called dispatched')
f = Bar()
f.bar('hoge') # called original
f.bar(770) # called dispatched
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment