Skip to content

Instantly share code, notes, and snippets.

@hwshim0810
Created March 6, 2018 04:08
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 hwshim0810/c4f86dda3af69dab78f16b5209d498ec to your computer and use it in GitHub Desktop.
Save hwshim0810/c4f86dda3af69dab78f16b5209d498ec to your computer and use it in GitHub Desktop.
Overloading in python
registry = {}
class MultiMethod(object):
def __init__(self, name):
self.name = name
self.typemap = {}
def __call__(self, *args):
# a generator expression
types = tuple(arg.__class__ for arg in args)
function = self.typemap.get(types)
if function is None:
raise TypeError("no match")
return function(*args)
def register(self, types, function):
if types in self.typemap:
raise TypeError("duplicate registration")
self.typemap[types] = function
def multimethod(*types):
def register(function):
name = function.__name__
mm = registry.get(name)
if mm is None:
mm = registry[name] = MultiMethod(name)
mm.register(types, function)
return mm
return register
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment