From 660956131e81d0dec429cfd9236eb75ad1553285 Mon Sep 17 00:00:00 2001 From: Tom Durrant Date: Fri, 20 Feb 2026 11:12:03 +1100 Subject: [PATCH] Add fuzzy typo detection to RompyBaseModel Raises helpful error messages when unknown field names are provided, suggesting close matches using difflib.get_close_matches with 0.6 cutoff. --- src/rompy/core/types.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/rompy/core/types.py b/src/rompy/core/types.py index c400dad6..7055d100 100644 --- a/src/rompy/core/types.py +++ b/src/rompy/core/types.py @@ -1,5 +1,6 @@ """Rompy types.""" +import difflib import json from datetime import datetime from typing import Any, Optional, Union @@ -11,6 +12,20 @@ class RompyBaseModel(BaseModel): # The config below prevents https://github.com/pydantic/pydantic/discussions/7121 model_config = ConfigDict(protected_namespaces=(), extra="forbid") + @model_validator(mode="before") + @classmethod + def check_for_typos(cls, data: Any) -> Any: + if isinstance(data, dict): + fields = cls.model_fields.keys() + for key in data.keys(): + if key not in fields: + matches = difflib.get_close_matches(key, fields, n=1, cutoff=0.6) + if matches: + raise ValueError( + f"Unknown field '{key}'. Did you mean '{matches[0]}'?" + ) + return data + def __init__(self, **data: Any): super().__init__(**data) self._original_inputs = data