Generate Python dataclasses with type hints, default values, and automatic method generation for structured data modeling
Generate Python dataclasses with automatic `__init__()`, `__repr__()`, `__eq__()`, and other special methods using the `@dataclass` decorator. Reduces boilerplate for data-focused classes with type annotations and sensible defaults.
This skill helps you create Python dataclasses following PEP 557 conventions. It automatically generates common dunder methods, handles default values and factories, supports frozen instances, inheritance patterns, and advanced features like keyword-only fields, slots, and custom field configurations.
When the user requests a Python dataclass:
1. **Understand Requirements**
- Ask about the data structure purpose and field names
- Determine which fields need default values
- Identify if any fields should be mutable (lists, dicts) requiring `default_factory`
- Check if the class should be frozen (immutable)
- Determine if comparison/ordering methods are needed
2. **Generate Basic Dataclass Structure**
```python
from dataclasses import dataclass
@dataclass
class ClassName:
"""Docstring describing the class purpose."""
field_name: type
field_with_default: type = default_value
```
3. **Apply Decorator Parameters as Needed**
- `frozen=True` for immutable instances
- `order=True` for comparison operators (`__lt__`, `__le__`, `__gt__`, `__ge__`)
- `kw_only=True` to make all fields keyword-only in `__init__()`
- `slots=True` for memory optimization (Python 3.10+)
- `eq=False` to disable equality comparison if not needed
4. **Handle Default Values Correctly**
- Use simple defaults for immutable types: `count: int = 0`
- Use `field(default_factory=list)` for mutable defaults to avoid shared state
- Use `field(default_factory=lambda: value)` for complex default logic
- Ensure fields without defaults come before fields with defaults
5. **Configure Field Behavior with `field()`**
```python
from dataclasses import dataclass, field
@dataclass
class Example:
# Exclude from repr
internal: str = field(repr=False)
# Exclude from comparison
metadata: dict = field(compare=False, default_factory=dict)
# Computed/init-only with default_factory
items: list[str] = field(default_factory=list)
```
6. **Handle Advanced Patterns**
- **Post-init processing**: Add `__post_init__(self)` method for validation or computed fields
- **Init-only variables**: Use `InitVar[type]` for parameters needed in `__post_init__()` but not stored
- **Class variables**: Use `ClassVar[type]` for shared class-level data
- **Inheritance**: Subclasses inherit parent fields; override defaults carefully
- **Frozen instances**: Use `frozen=True` for immutable objects with automatic `__hash__()`
7. **Add Methods When Needed**
- Custom business logic methods can be added normally
- Override generated methods if custom behavior is required
- Use `__post_init__()` for validation or derived field computation
8. **Follow Best Practices**
- Always include type annotations (required for dataclasses)
- Use descriptive field names and class docstrings
- Prefer `frozen=True` for value objects and data transfer objects
- Use `field(repr=False)` for sensitive data (passwords, tokens)
- Leverage `field(compare=False)` for fields that shouldn't affect equality (timestamps, metadata)
- Use slots for memory-critical applications or large numbers of instances
```python
from dataclasses import dataclass
@dataclass
class InventoryItem:
"""Class for keeping track of an item in inventory."""
name: str
unit_price: float
quantity_on_hand: int = 0
def total_cost(self) -> float:
return self.unit_price * self.quantity_on_hand
```
```python
from dataclasses import dataclass
@dataclass(frozen=True)
class DatabaseConfig:
"""Immutable database configuration."""
host: str
port: int = 5432
database: str = "postgres"
ssl: bool = True
```
```python
from dataclasses import dataclass, field
@dataclass
class Project:
"""Project with team members and tags."""
name: str
owner: str
members: list[str] = field(default_factory=list)
tags: set[str] = field(default_factory=set)
metadata: dict[str, str] = field(default_factory=dict, repr=False)
```
```python
from dataclasses import dataclass
@dataclass
class User:
username: str
email: str
age: int
def __post_init__(self):
if self.age < 0:
raise ValueError("Age cannot be negative")
if "@" not in self.email:
raise ValueError("Invalid email address")
```
```python
from dataclasses import dataclass
@dataclass(order=True)
class Priority:
"""Task priority with automatic ordering."""
level: int
name: str = field(compare=False) # Don't compare name for ordering
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/python-dataclasses-generator/raw