Skip to content

Instantly share code, notes, and snippets.

@pohlt
Created January 18, 2024 19:25
Show Gist options
  • Save pohlt/83cae39aee9545251c3f1573fe041e57 to your computer and use it in GitHub Desktop.
Save pohlt/83cae39aee9545251c3f1573fe041e57 to your computer and use it in GitHub Desktop.
Python pattern matching of self-made classes
class C:
__match_args__ = ("__match_self_prop__",)
def __init__(self, x, y=42):
self.x = x
self.y = y
@property
def __match_self_prop__(self):
return self
def __str__(self):
return f"C({self.x=}, {self.y=})"
s = C(17)
print("Hello world")
match s:
case int(s):
print("int")
case str(s):
print("string")
case C(s) as c:
print("C", c)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment