Skip to content

Instantly share code, notes, and snippets.

@darkfeline
Last active August 29, 2015 14:08
Show Gist options
  • Save darkfeline/a611fa1ea494a98424ec to your computer and use it in GitHub Desktop.
Save darkfeline/a611fa1ea494a98424ec to your computer and use it in GitHub Desktop.
Python multimethods (Clojure style)
class MultiMethod:
def __init__(self, func):
self.func = func
self.methods = {}
def __call__(self, *args, **kwargs):
return self.methods[self.func(*args, **kwargs)](*args, **kwargs)
def method(self, case):
def method_adder(func):
self.methods[case] = func
return self
return method_adder
to_string = MultiMethod(lambda x: x.__class__)
@to_string.method(str)
def to_string(self):
return "string"
@to_string.method(int)
def to_string(self):
return "integer"
print(to_string("hi"))
print(to_string(1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment