Brandon Rozek

Photo of Brandon Rozek

PhD Student @ RPI studying Automated Reasoning in AI and Linux Enthusiast.

Quick Python: Dataclasses

Published on

Updated on

Warning: This post has not been modified for over 2 years. For technical posts, make sure that it is still relevant.

Python 3.7 and above have a feature called dataclasses. This allows us to reduce boilerplate code by removing the need to create a whole constructor and providing a sensible __repr__ function.

from dataclasses import dataclass

class Person:
    name: str
    age: int = 0


p = Person("Bob", 30)
Person(name='Bob', age=20)

To make an attribute have a default value, add it after the type declaration like I have with age.

Reply via Email Buy me a Coffee
Was this useful? Feel free to share: Hacker News Reddit Twitter

Published a response to this? :