# Dataclasses & Enums — Python Fundamentals: From Basics to Async

Source: https://www.geekswithgeeks.com/en/python/py-dataclasses-enums

> Cut boilerplate with @dataclass for data-holding classes and use Enum for fixed sets of named constants.

## @dataclass

`@dataclass` generates `__init__`, `__repr__` and `__eq__` from type-annotated fields, so data classes need no boilerplate.

```python
from dataclasses import dataclass, field

@dataclass
class User:
    name: str
    age: int = 0
    tags: list[str] = field(default_factory=list)

u = User("Ada", 36)
print(u)            # User(name='Ada', age=36, tags=[])
print(u == User("Ada", 36))  # True
```

## Enum

`Enum` names a fixed set of values, so code reads `Status.ACTIVE` instead of a magic string.

```python
from enum import Enum

class Status(Enum):
    PENDING = "pending"
    ACTIVE = "active"

s = Status("active")
print(s, s.name, s.value)   # Status.ACTIVE ACTIVE active
```

Use `field(default_factory=list)` for mutable defaults. Add `frozen=True` to make a dataclass immutable and hashable.

Quick check

**Quiz:** Which methods does @dataclass generate automatically?

- [x] __init__, __repr__ and __eq__
- [ ] Only __del__
- [ ] __enter__ and __exit__
- [ ] None of them

*Answer:* __init__, __repr__ and __eq__. Dataclasses generate these from the annotated fields.
