Last active
October 31, 2023 19:54
-
-
Save masahitojp/eff33a4c0ac3293d4a901b580a9907eb to your computer and use it in GitHub Desktop.
Try pattern matching + dataclass in python 3.10
This file contains 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
import dataclasses | |
@dataclasses.dataclass | |
class User: | |
name: str | |
age: int = 0 | |
if __name__ == "__main__": | |
u = User("taro", 32) | |
match u: | |
case User(name, age): | |
print(f"{name}, {age}") |
This file contains 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 abc import ABC | |
from dataclasses import dataclass | |
@dataclass | |
class AbstractDataclass(ABC): | |
def __new__(cls, *args, **kwargs): | |
if cls == AbstractDataclass or cls.__bases__[0] == AbstractDataclass: | |
raise TypeError("Cannot instantiate abstract class.") | |
return super().__new__(cls) | |
@dataclass | |
class User(AbstractDataclass): | |
name: str | |
age: int = 0 | |
@dataclass | |
class PaidUser(User): | |
plan: str = "starter" | |
@dataclass | |
class FreeUser(User): | |
pass | |
if __name__ == "__main__": | |
u = PaidUser("taro", 32) | |
match u: | |
case PaidUser(name, age, plan): | |
print(f"PaidUser: {name}, {age}, {plan}") | |
case FreeUser(name, age): | |
print(f"FreeUser: {name}, {age}") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment