This post is about 90% inspired by What to Know Before Debating Type Systems and 10% inspired by Type Systems: The Good, Bad, and Ugly. In the former, Smith makes the point that static typing and dynamic typing use fundamentally different definitions of what a ‘type’ is. Static typing is a property of the code, while dynamic typing is about runtime behavior. That’s gotten me interested in what you can really do with dynamic typing. All of the arguments online assume it’s just “no static” so it’s easier to prototype. “Here’s something annoying you don’t have to deal with.” I want to hear more about the kinds of tricks that would be hard or impossible to replicate in static type systems. Note it doesn’t have to be a good engineering or production quality or anything. I just want to know about interesting things.
Here’s my contribution: Python has Abstract Base Classes. In addition to the usual ways those are defined, Python ABCs have a special method called
__subclasshook__. This lets you define at runtime what classes are considered subclasses of the ABC. For example:
from abc import ABC class CoordinateAbc(ABC): @classmethod def __subclasshook__(cls, other): return all((hasattr(other, method) for method in ['__add__', '__sub__', '__abs__']))
Then any object you could reasonably use as a coordinate in a coordinate system is considered an instance of CoordinateAbc. You can also define subclasshooks like “classes that have at least one method with
lru_cache” or “classes that are used as arguments when initializing some other class”.