Member-only story
The Power of Polymorphism in Python
The Secret Sauce Behind Julia and Lisp — Now in Python
Have you ever wished your Python functions could respond more smartly — like really smartly — depending on all the argument types passed in? That’s multiple dispatch. It’s like function overloading’s cooler, more flexible cousin, and it’s built into languages like Julia and Common Lisp (via CLOS). But in Python? Well, it takes some extra work.
Let me take you on a little journey — story-first, code-always — to show you what works, what doesn’t, and what will save you time and sanity.
Part 1: Trying multipledispatch (And Seeing Where It Cracks)
Let’s say we’re writing a program that greets people differently based on whether they’re Vegan, Vegetarian, or just a regular Person. Sounds easy?
Let’s start with the multipledispatch package:
from multipledispatch import dispatch
class Person:
pass
class Vegan(Person):
pass
class Vegetarian(Person):
pass
@dispatch(Vegan, str)
def greet(person, name):
return f"Hi, I'm {name}! I'm a vegan!"
@dispatch(Vegetarian, str)
def greet(person, name):
return f"Hi, I'm {name}! I'm a vegetarian!"
@dispatch(Person, str)
def greet(person, name):
return f"Hi, I'm {name}…
