Hasty Briefsbeta

Crimes with Python's Pattern Matching (2022)

2 days ago
  • #Python
  • #Abstract Base Classes
  • #Pattern Matching
  • Python's `__subclasshook__` in Abstract Base Classes (ABCs) allows defining custom subclass checks, enabling unconventional type matching.
  • Python 3.10's pattern matching interacts with ABCs via `isinstance()`, allowing ABCs to influence match cases based on dynamic conditions.
  • Example: `NotIterable` ABC hijacks pattern matching by checking for the absence of `__iter__`, demonstrating unexpected behavior.
  • Pattern matching can destructure object fields, and ABCs can dynamically match objects with specific attributes (e.g., `DistanceMetric`).
  • Combinators like `Not` and `And` can be created at runtime to compose complex matching logic, though syntax constraints exist.
  • Side effects in `__subclasshook__` (e.g., caching, user prompts) are possible but discouraged due to unpredictability.
  • Warning: Misusing `__subclasshook__` for pattern matching is considered dark magic and not recommended for production code.