Created
April 25, 2011 12:15
-
-
Save gmarkall/940427 to your computer and use it in GitHub Desktop.
mm module (by Guido van Rossum)
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
registry = {} | |
class MultiMethod(object): | |
def __init__(self, name): | |
self._name = name | |
self._typemap = {} | |
def __call__(self, *args): | |
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): | |
function = getattr(function, "__lastreg__", function) | |
name = function.__name__ | |
mm = registry.get(name) | |
if mm is None: | |
mm = registry[name] = MultiMethod(name) | |
mm.register(types, function) | |
mm.__lastreg__ = function | |
return mm | |
return register |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment