Blame
|
1 | # Dataclass |
||||||
| 2 | A **dataclass** is a Python feature that automatically generates common methods (such as `__init__`,` __repr__`, and `__eq__`) for classes that primarily store data. It reduces boilerplate code and makes data models easier to read and maintain. |
|||||||
| 3 | ||||||||
| 4 | ## Overview |
|||||||
| 5 | ```python |
|||||||
| 6 | from dataclasses import dataclass |
|||||||
| 7 | ||||||||
| 8 | @dataclass(slots=True, frozen=True) |
|||||||
| 9 | class search_element: |
|||||||
| 10 | ... |
|||||||
| 11 | ``` |
|||||||
| 12 | ||||||||
| 13 | ## `slots=True` |
|||||||
| 14 | Using slots=True creates a fixed set of attributes for each instance instead of a dynamic `__dict__`. |
|||||||
| 15 | ||||||||
| 16 | Benefits: |
|||||||
| 17 | - Reduces memory usage. |
|||||||
| 18 | - Improves attribute access performance. |
|||||||
| 19 | - Prevents adding new attributes at runtime. |
|||||||
| 20 | ||||||||
| 21 | ## `frozen=True` |
|||||||
| 22 | Using frozen=True makes instances effectively immutable after creation. |
|||||||
| 23 | ||||||||
| 24 | Benefits: |
|||||||
| 25 | - Prevents accidental modification of object state. |
|||||||
| 26 | - Makes objects safer to share across code. |
|||||||
| 27 | - Allows instances to be hashable (when appropriate), so they can be used as dictionary keys or stored in sets. |
|||||||
