refactor(community): remove dead __new__ coercion, validate before field assignment
This commit is contained in:
parent
2e9e3fdc4b
commit
a189511760
1 changed files with 11 additions and 15 deletions
|
|
@ -66,29 +66,25 @@ class CommunityPost:
|
||||||
protein_pct: float | None
|
protein_pct: float | None
|
||||||
moisture_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):
|
def __init__(self, **kwargs):
|
||||||
# Convert lists to tuples
|
# 1. Coerce list fields to tuples
|
||||||
for key in ("slots", "dietary_tags", "allergen_flags", "flavor_molecules"):
|
for key in ("slots", "dietary_tags", "allergen_flags", "flavor_molecules"):
|
||||||
if key in kwargs and isinstance(kwargs[key], list):
|
if key in kwargs and isinstance(kwargs[key], list):
|
||||||
kwargs[key] = tuple(kwargs[key])
|
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:
|
# 2. Validate BEFORE assignment
|
||||||
if self.post_type not in _VALID_POST_TYPES:
|
post_type = kwargs.get("post_type")
|
||||||
|
if post_type not in _VALID_POST_TYPES:
|
||||||
raise ValueError(
|
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 (
|
for score_name in (
|
||||||
"seasoning_score", "richness_score", "brightness_score",
|
"seasoning_score", "richness_score", "brightness_score",
|
||||||
"depth_score", "aroma_score", "structure_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])
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue