2020-04-08 23:05:28 +00:00
---
title: "Quick Python: Dataclasses"
date: 2020-04-08T18:59:48-04:00
draft: false
2022-01-02 19:24:29 +00:00
tags: ["Python"]
2023-01-05 19:04:45 +00:00
medium_enabled: true
2020-04-08 23:05:28 +00:00
---
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.
```python
from dataclasses import dataclass
@dataclass
class Person:
name: str
2020-05-01 03:18:42 +00:00
age: int = 0
2020-04-08 23:05:28 +00:00
```
Usage:
```python
p = Person("Bob", 30)
print(p)
```
```
Person(name='Bob', age=20)
```
2020-05-01 03:18:42 +00:00
To make an attribute have a default value, add it after the type declaration like I have with `age` .