Skip to content

Commit

Permalink
🔥 match for python added.
Browse files Browse the repository at this point in the history
Suprisingly, `__match_args__` can be a property.
  • Loading branch information
rentruewang committed Jul 8, 2024
1 parent 3553de6 commit 6de446d
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions python/src/matching.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Copyright (c) 2024 RenChu Wang - All Rights Reserved

import dataclasses as dcls


@dcls.dataclass(frozen=True)
class DataClass:
name: str
value: int


class MissingMatcher:
__match_args__ = "hello", "world"

@property
def hello(self):
return "hello"


class CustomMatcher:
@property
def __match_args__(self):
# Property is ok as well.
return "hello", "world"

@property
def hello(self):
return "hello"

@property
def world(self):
return "world"


if __name__ == "__main__":
dc = DataClass(name="name", value=3)

match dc:
case DataClass(name=n, value=v):
print(n, v)
case _:
raise ValueError

# mm = MissingMatcher()

# match mm:
# # Not matching
# case MissingMatcher(hello=h, world=w):
# print(h, w)
# case _:
# raise ValueError

cm = CustomMatcher()

match cm:
case CustomMatcher(hello=h, world=w):
print(h, w)
case _:
raise ValueError

0 comments on commit 6de446d

Please sign in to comment.