What is a dataclass and why use one in automation code?
IntermediateConceptLanguage essentials & functions
Answer
@dataclass generates __init__, __repr__ and __eq__ from annotated fields. It gives you typed, self-documenting records instead of dicts with magic string keys.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Finding:
check: str
resource_id: str
severity: str = "LOW"
tags: dict[str, str] = field(default_factory=dict)
frozen=True makes it immutable and hashable; field(default_factory=...) avoids the mutable default bug; asdict() turns it into JSON-ready data. For validation of untrusted input, pydantic models go further.
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner