refactor(community): remove dead __new__ coercion, validate before field assignment

This commit is contained in:
pyr0ball 2026-04-12 21:11:41 -07:00
parent 2e9e3fdc4b
commit a189511760

View file

@ -66,29 +66,25 @@ class CommunityPost:
protein_pct: float | None
moisture_pct: float | None
def __new__(cls, **kwargs):
# Convert lists to tuples before frozen dataclass assignment
for key in ("slots", "dietary_tags", "allergen_flags", "flavor_molecules"):
if key in kwargs and isinstance(kwargs[key], list):
kwargs[key] = tuple(kwargs[key])
return object.__new__(cls)
def __init__(self, **kwargs):
# Convert lists to tuples
# 1. Coerce list fields to tuples
for key in ("slots", "dietary_tags", "allergen_flags", "flavor_molecules"):
if key in kwargs and isinstance(kwargs[key], list):
kwargs[key] = tuple(kwargs[key])
for f in self.__dataclass_fields__:
object.__setattr__(self, f, kwargs[f])
self.__post_init__()
def __post_init__(self) -> None:
if self.post_type not in _VALID_POST_TYPES:
# 2. Validate BEFORE assignment
post_type = kwargs.get("post_type")
if post_type not in _VALID_POST_TYPES:
raise ValueError(
f"post_type must be one of {sorted(_VALID_POST_TYPES)}, got {self.post_type!r}"
f"post_type must be one of {sorted(_VALID_POST_TYPES)}, got {post_type!r}"
)
for score_name in (
"seasoning_score", "richness_score", "brightness_score",
"depth_score", "aroma_score", "structure_score",
):
_validate_score(score_name, getattr(self, score_name))
if score_name in kwargs:
_validate_score(score_name, kwargs[score_name])
# 3. Assign all fields
for f in self.__dataclass_fields__:
object.__setattr__(self, f, kwargs[f])