Skip to content

Instantly share code, notes, and snippets.

@xinbinhuang
Last active July 3, 2020 17:39
Show Gist options
  • Save xinbinhuang/eb06f694f17607ba8f94bb5bc77800eb to your computer and use it in GitHub Desktop.
Save xinbinhuang/eb06f694f17607ba8f94bb5bc77800eb to your computer and use it in GitHub Desktop.
How to get a dict of attributes from a (data)class
from dataclasses import dataclass, field, asdict
import random
from faker import Faker
faker = Faker()
@dataclass
class Purchase:
username: str = field(default_factory=faker.user_name)
currency: str = field(default_factory=faker.currency_code)
amount: int = field(default_factory=lambda: random.randint(100, 200000))
p = Purchase()
assert vars(p) == asdict(p)
# True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment