Created
August 12, 2019 19:01
-
-
Save eddieantonio/d09a17353cae856a5b4fe8adbfe0e740 to your computer and use it in GitHub Desktop.
Showcase of dataclasses and module __getattr__().
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
#!/usr/bin/env python3 | |
# -*- coding: UTF-8 -*- | |
from dataclasses import dataclass | |
from random import randint | |
import re | |
dn = re.compile(r'd([123456789][0123456789]*)') | |
__all__ = ['Die'] | |
@dataclass(frozen=True) | |
class Die: | |
sides: int | |
def roll(self): | |
return randint(1, self.sides) | |
def __getattr__(name): | |
match = dn.match(name) | |
if match is not None: | |
sides = int(match.group(1)) | |
return Die(sides) | |
raise AttributeError(f"module {__name__} has no attribute {name}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment