Polymorphism
Polymorphism in Python
"Polymorphism means using one symbol to represent multiple different types." — Bjarne Stroustrup, The C++ Programming Language
Core idea
Polymorphism is the ability of one call (method, operator, function) to behave differently depending on the type of the argument. It is the main mechanism that lets you write code that works with any object of the right "shape", without knowing the concrete type.
Three forms of polymorphism
The classic taxonomy (Cardelli & Wegner, 1985): subtype, parametric, ad-hoc. To these we add structural as the practical cousin of structural subtyping in languages with duck typing.
| Form | What it is | Example in Python |
|---|---|---|
| Subtype | A base class method is overridden in a child | EmailNotifier.send overrides Notifier.send |
| Structural | A type "fits" because it has the right methods (no explicit inheritance) | Duck typing, Protocol, len("abc") / len([1,2]) via __len__ |
| Parametric | One piece of code for many types via a type parameter | list[T], dict[K, V], TypeVar, generics |
| Ad-hoc | A separate implementation per type (overloading) | @functools.singledispatch, @overload declarations for mypy |
Static languages (Java, C#) lean on subtype polymorphism. Python leans on structural through dunder methods and duck typing. That is a real difference.
1. Subtype polymorphism — through override
The classic textbook example:
class Shape:
def area(self) -> float:
raise NotImplementedError
class Circle(Shape):
def __init__(self, r: float):
self.r = r
def area(self) -> float:
return 3.14159 * self.r ** 2
class Rectangle(Shape):
def __init__(self, w: float, h: float):
self.w, self.h = w, h
def area(self) -> float:
return self.w * self.h
shapes: list[Shape] = [Circle(5), Rectangle(3, 4)]
for s in shapes:
print(s.area()) # ← one call, different behaviour
This works, but in Python it is not the best pattern. Try this instead.
Why Protocol is better in Python
Same task without inheritance:
from typing import Protocol
class HasArea(Protocol):
def area(self) -> float: ...
class Circle: # ← does NOT inherit Shape
def __init__(self, r): self.r = r
def area(self): return 3.14159 * self.r ** 2
class Rectangle: # ← also no inheritance
def __init__(self, w, h): self.w, self.h = w, h
def area(self): return self.w * self.h
shapes: list[HasArea] = [Circle(5), Rectangle(3, 4)]
Advantages:
- No inheritance, no fragile base class.
- You can include a class you do not control (for example,
shapely.geometry.Point, which hasarea). - Fewer connections.
Takeaway: subtype polymorphism through ABC only makes sense when you need a template method or a runtime guarantee. Otherwise reach for Protocol.
Rules for overriding methods
Override is a dangerous operation. Follow three rules so you do not break the caller.
1. Same signature (or compatible)
class Base:
def process(self, x: int) -> str: ...
class Child(Base):
def process(self, x: int) -> str: ... # ✅ same signature
class BrokenChild(Base):
def process(self, x: int, y: int) -> str: ... # ❌ changed signature
2. Same contract (LSP)
The subclass must not:
- raise new exceptions that the parent did not raise,
- return a "narrower" type that fails the parent contract,
- have stricter preconditions (extra validation, for example).
class Bird:
def fly(self) -> None: ...
class Penguin(Bird):
def fly(self) -> None:
raise NotImplementedError # ❌ contract said "flies", you said "I do not fly"
This is an LSP violation, the L in SOLID.
3. Call super() when you want to extend, not replace
class Base:
def __init__(self, name):
self.name = name
self.created_at = datetime.now()
class Child(Base):
def __init__(self, name, extra):
super().__init__(name) # ← run the parent's init
self.extra = extra
Without super().__init__() you do not get self.created_at and every method that depends on it breaks.
2. Structural polymorphism — duck typing and dunder methods
This is the heart of Python. The principle: "if it quacks like a duck, it's a duck".
A simple example: len()
len("abc") # 3 — string
len([1, 2, 3]) # 3 — list
len({1, 2}) # 2 — set
len({"a": 1}) # 1 — dict
None of these types inherits from a Sized class. So how does len() work for all of them? Through the __len__ dunder method:
class MyCollection:
def __init__(self): self._items = [1, 2, 3]
def __len__(self): return len(self._items)
len(MyCollection()) # 3 ✅
len() is just a call to __len__() under the hood. Any class that defines __len__ is automatically compatible with len().
This is real Python polymorphism: not "inherit from
Sized", but "implement the dunder and you are part of the ecosystem".
Catalog of the most important dunder methods
Equality and hash
| Method | What it gives you |
|---|---|
__eq__(self, other) |
the == operator |
__hash__(self) |
lets the object live in a set or as a dict key |
⚠️ Rule: overriding __eq__ automatically sets __hash__ = None. The class becomes unhashable (cannot live in a set or as a dict key). If you need it hashable, define __hash__ explicitly (for example, return hash((self.a, self.b))) or use @dataclass(frozen=True), which does it for you.
Ordering
| Method | What it gives you |
|---|---|
__lt__(self, other) |
< |
__le__(self, other) |
<= |
__gt__(self, other) |
> |
__ge__(self, other) |
>= |
💡 Instead of writing all four, use @functools.total_ordering:
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, major, minor): self.major, self.minor = major, minor
def __eq__(self, other): return (self.major, self.minor) == (other.major, other.minor)
def __lt__(self, other): return (self.major, self.minor) < (other.major, other.minor)
# now <=, >, >= are generated automatically
Arithmetic
| Method | What it gives you |
|---|---|
__add__(self, other) |
+ |
__sub__(self, other) |
- |
__mul__(self, other) |
* |
__truediv__(self, other) |
/ |
__floordiv__(self, other) |
// |
__mod__(self, other) |
% |
__neg__(self) |
unary -x |
__abs__(self) |
abs(x) |
Binary operators have an r-version for the right-hand call (__radd__ for 2 + my_obj when (2).__add__(my_obj) returns NotImplemented). Unary operators (__neg__, __abs__) have no r-version, because there is no second side.
Representation
| Method | What it gives you | Audience |
|---|---|---|
__repr__(self) |
repr(x), REPL output |
Developers — diagnostics, debug |
__str__(self) |
str(x), print(x), f-string |
Users — human output |
⚠️ If you only have __repr__, str() falls back to it. If you only have __str__, repr() gives you the default <MyClass object at 0x...>. Always define __repr__ at the minimum.
Container protocol
| Method | What it gives you |
|---|---|
__len__(self) |
len(x), bool(x) (if __bool__ is missing) |
__iter__(self) |
for x in obj, list(obj) |
__contains__(self, item) |
item in obj |
__getitem__(self, key) |
obj[key] |
__setitem__(self, key, val) |
obj[key] = val |
__delitem__(self, key) |
del obj[key] |
__bool__(self) |
bool(x), if x: |
Context manager (with)
| Method | What it gives you |
|---|---|
__enter__(self) |
start of the with block |
__exit__(self, ...) |
end (including errors) |
Callable
| Method | What it gives you |
|---|---|
__call__(self, *args) |
obj() — call the object like a function |
This is real power: your object can behave like a function, a collection, a number, or a context manager, just by implementing the right dunders.
3. Ad-hoc polymorphism — @singledispatch
Python does not have function overloading the way Java or C# do (void process(int), void process(String)). Instead, you have functools.singledispatch:
from functools import singledispatch
@singledispatch
def format_value(value) -> str:
return str(value) # ← default
@format_value.register
def _(value: int) -> str:
return f"INT: {value:,}"
@format_value.register
def _(value: float) -> str:
return f"FLOAT: {value:.2f}"
@format_value.register
def _(value: list) -> str:
return f"LIST({len(value)}): {value}"
format_value(42) # "INT: 42"
format_value(3.14) # "FLOAT: 3.14"
format_value([1,2,3]) # "LIST(3): [1, 2, 3]"
format_value("hi") # "hi" (default)
This is dispatch on the type of the first argument. Useful for:
- serialisation (different JSON shape per type),
- formatting,
- pattern dispatch (Visitor pattern without classes).
Alternative:
if isinstance(...)chains.singledispatchis cleaner and easier to extend.
Type hints and polymorphism
@overload — signature variants for the type checker
from typing import overload
@overload
def get(key: str) -> str | None: ...
@overload
def get(key: str, default: str) -> str: ...
def get(key, default=None): # the real implementation
return cache.get(key, default)
x = get("name") # mypy knows: x: str | None
y = get("name", "anonymous") # mypy knows: y: str (default is present)
These hints are for the static analyser only. At runtime there is one body. Useful for APIs with different usage variants.
Anti-patterns
1. isinstance chains instead of polymorphism
# ❌ Anti-pattern
def area(shape):
if isinstance(shape, Circle):
return 3.14 * shape.r ** 2
elif isinstance(shape, Rectangle):
return shape.w * shape.h
elif isinstance(shape, Triangle):
return ...
Every new type needs a change in area(). Put the method on the class instead:
# ✅ Right
class Circle:
def area(self): return 3.14 * self.r ** 2
class Rectangle:
def area(self): return self.w * self.h
This is "ask, don't check the type". Ask the object what it can do, do not ask "what are you?".
Exception: @singledispatch for functions that do not belong to a class.
2. Override that replaces super() entirely
class Base:
def init_db(self):
self._setup_logging()
self._connect_to_db()
self._migrate()
class Child(Base):
def init_db(self):
self._connect_to_db() # ← skipped logging and migrate
If you do not call super(), you are doing something completely different. You probably wanted a new method, not an override.
3. Dunders with side effects
class BadCart:
def __len__(self):
self._save_to_db() # ❌ len() writes to the DB?!
return len(self._items)
Dunder methods must behave the way callers expect. len() is supposed to be fast, no I/O. Otherwise everyone is surprised.
Rule: dunders are the language's contract. Behave like
int,list,dictwould.
4. __eq__ without __hash__
class Money:
def __init__(self, amount): self.amount = amount
def __eq__(self, other):
return isinstance(other, Money) and self.amount == other.amount
m1 = Money(100)
{m1} # ❌ TypeError: unhashable type: 'Money'
Overriding __eq__ automatically sets __hash__ = None. Either implement __hash__ or use @dataclass(frozen=True).
5. Polymorphism for the sake of polymorphism
class IShape:
def render(self) -> str: ...
class Square(IShape): # the only implementation, forever
def render(self): return "▦"
One implementation means no interface needed. YAGNI. Wait for the second case.
Rules of thumb
- Before writing an
isinstancechain, ask whether you can do it polymorphically. - Protocol as the default interface. ABC only when you need a template method.
- Override only with the same signature and the same contract (LSP).
- Dunder methods with no side effects. That is the language's contract.
__eq__and__hash__are a pair. Or use a frozen dataclass.__repr__always.__str__when you need a human-friendly format.functools.total_orderinginstead of writing four comparison methods by hand.@singledispatchwhen the logic varies by type and the function does not belong to a class.
One-line summary
Polymorphism means the same call works for anything with the right "shape". In Python, the shape is defined by dunder methods and Protocol, not by inheritance.