Created
January 22, 2025 20:26
-
-
Save bpeterso2000/efe7f0fa94eeb222f405a1a6cad54bda to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from enum import Enum | |
from functools import singledispatch | |
class Color(Enum): | |
RED = 1 | |
GREEN = 2 | |
BLUE = 3 | |
@singledispatch | |
def process(color: Color, *args, **kwargs): | |
print(f"Default case for color: {color}, args: {args}, kwargs: {kwargs}") | |
@process.register(Color.RED) | |
def _(color: Color.RED, *args, **kwargs): | |
print(f"Processing RED with args: {args}, kwargs: {kwargs}") | |
@process.register(Color.GREEN) | |
def _(color: Color.GREEN, *args, **kwargs): | |
print(f"Processing GREEN with args: {args}, kwargs: {kwargs}") | |
@process.register(Color.BLUE) | |
def _(color: Color.BLUE, *args, **kwargs): | |
print(f"Processing BLUE with args: {args}, kwargs: {kwargs}") | |
# Example usage | |
process(Color.RED, 1, 2, 3, a="apple", b="banana") # Calls RED handler | |
process(Color.GREEN, "green", "lime", shade="light") # Calls GREEN handler | |
process(Color.BLUE, "sky", "ocean", depth=100) # Calls BLUE handler | |
process(Color(4), "unknown", "color") # Falls back to default case |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment