> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Data Class

A data class is a class decorated with `@dataclass` from the `dataclasses` module, introduced in Python 3.7. It utilizes PEP 526 variable annotations to automatically generate boilerplate special methods (dunder methods)—such as `__init__()`, `__repr__()`, and `__eq__()`—directly into the class namespace based on the defined attributes.

## Basic Syntax

To define a data class, apply the `@dataclass` decorator and declare class variables with type hints.

```python theme={"dark"}
from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float
    z: float = 0.0  # Attribute with a default value
```

When the Python interpreter processes this decorator, it dynamically synthesizes the following methods:

1. **`__init__(self, x: float, y: float, z: float = 0.0)`**: Initializes the instance variables.
2. **`__repr__(self)`**: Returns a string representation, e.g., `Point(x=1.0, y=2.0, z=0.0)`.
3. **`__eq__(self, other)`**: Compares the class instances as if they were tuples of their fields.

## Decorator Parameters

The `@dataclass` decorator accepts several boolean arguments to control which methods are generated and how the class behaves:

```python theme={"dark"}
@dataclass(
    init=True,         # Generates __init__()
    repr=True,         # Generates __repr__()
    eq=True,           # Generates __eq__()
    order=False,       # Generates __lt__(), __le__(), __gt__(), __ge__()
    unsafe_hash=False, # Forces generation of __hash__()
    frozen=False,      # Makes instances immutable (read-only)
    match_args=True,   # Generates __match_args__ for structural pattern matching
    kw_only=False,     # Forces all fields to be keyword-only arguments (Python 3.10+)
    slots=False        # Generates __slots__ for memory optimization (Python 3.10+)
)
class Configuration:
    pass
```

Setting `frozen=True` simulates immutability by overriding `__setattr__()` and `__delattr__()` to raise a `FrozenInstanceError` if attribute modification is attempted after initialization. It also automatically generates a `__hash__()` method, making the instances hashable.

## The `field()` Function

For granular control over individual attributes, the `field()` function is used. It allows you to exclude specific fields from generated methods or handle mutable default values.

```python theme={"dark"}
from dataclasses import dataclass, field
from typing import List

@dataclass
class Node:
    id: int
    # default_factory prevents shared state across instances for mutable types
    children: List['Node'] = field(default_factory=list)
    
    # Exclude from __repr__ and __init__
    internal_cache: dict = field(default_factory=dict, repr=False, init=False)
```

Key parameters of `field()` include:

* `default`: The default value for the field.
* `default_factory`: A zero-argument callable called to initialize a field's value (required for mutable types like `list` or `dict`).
* `init`: If `False`, the field is excluded from the generated `__init__()`.
* `repr`: If `False`, the field is excluded from the generated `__repr__()`.
* `compare`: If `False`, the field is excluded from generated equality and ordering methods.

## Post-Initialization Processing

Because the `@dataclass` decorator overwrites the `__init__()` method, custom initialization logic cannot be placed there. Instead, the `dataclasses` module provides the `__post_init__()` hook.

If defined on the class, the generated `__init__()` method will automatically call `__post_init__()` immediately after all fields have been initialized.

```python theme={"dark"}
@dataclass
class Rectangle:
    width: float
    height: float
    area: float = field(init=False)

    def __post_init__(self):
        # Executes after width and height are bound to self
        self.area = self.width * self.height
```

If the class is defined with `frozen=True`, `__post_init__()` must use `object.__setattr__(self, 'name', value)` to bypass the immutability constraints during the post-initialization phase.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Python Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
