Skip to content

Instantly share code, notes, and snippets.

@eddieantonio eddieantonio/dice.py
Created Aug 12, 2019

Embed
What would you like to do?
Showcase of dataclasses and module __getattr__().
#!/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
You can’t perform that action at this time.