source: kdnuggets: stop using if-else chains: use the registry pattern in python instead
level: technical
long if-else chains in python code become hard to maintain as new cases are added. they violate the open/closed principle, mix unrelated logic, and cannot be extended from outside. a simple dictionary lookup can replace the chain, giving constant-time dispatch and making options easy to list. however, a hand-maintained dictionary still requires editing the central file for each new entry.
a decorator-based registry lets each function or class register itself with a key. the dispatcher stays small and never changes. new handlers are added by writing a function with a decorator in any file, with no need to modify the central dispatcher. this approach keeps related code together and avoids merge conflicts. for multiple registries, a reusable registry class adds collision detection and better error messages.
for class-based registries, python's __init_subclass__ hook can auto-register subclasses without decorators. this pattern is used in many frameworks for plugin systems. it is useful in machine learning configs, file format dispatch, web routing, and event handling. be aware that registration only happens on import, so modules must be imported explicitly. guard against silent key overwrites and always show available keys in error messages. use the pattern when dispatching on discrete keys to interchangeable behaviors that are expected to grow.
why it matters: using the registry pattern makes python code more maintainable and extensible, especially in ai and data science projects where new models, data loaders, or processing steps are frequently added.
source: kdnuggets: stop using if-else chains: use the registry pattern in python instead