Skip to content

Instantly share code, notes, and snippets.

@masahitojp
Last active October 31, 2023 19:54
Show Gist options
  • Save masahitojp/eff33a4c0ac3293d4a901b580a9907eb to your computer and use it in GitHub Desktop.
Save masahitojp/eff33a4c0ac3293d4a901b580a9907eb to your computer and use it in GitHub Desktop.
Try pattern matching + dataclass in python 3.10
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}")
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