fix: access model_fields from class instead of instance#663
fix: access model_fields from class instead of instance#663sene03 wants to merge 1 commit intoapache:mainfrom
Conversation
Fixes deprecation warning in Pydantic 2.11+ where accessing model_fields on an instance is deprecated. Changed to use type(model).model_fields in model_to_dict(). Closes apache#652 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
@sene03 I think we need a minimum version pin in pyproject.toml with this change -- do you know what that would be? |
|
you need to pair this with #654 |
andreahlert
left a comment
There was a problem hiding this comment.
Tested locally with pydantic 2.12.5. This is the correct and minimal fix - model_to_dict is the only function that accesses model_fields on an instance. The other functions (subset_model, model_from_state, _validate_keys) already receive classes via Type[BaseModel] and never triggered the deprecation. Clean fix, no unnecessary changes.
Re @skrawcz's comment about version pins: type(model).model_fields works on all pydantic 2.x - no minimum bump is strictly required for this fix. If a pin is desired for other reasons, PR #654 already handles that separately, which is the right separation of concerns.
One suggestion: add a behavioral test that asserts no DeprecationWarning is emitted from model_to_dict, rather than just testing the output. This would catch regressions if someone reverts to instance access:
import warnings
def test_model_to_dict_no_deprecation_warning():
model = OriginalModel(foo=1, bar="bar", nested=NestedModel(nested_field1=1))
with warnings.catch_warnings():
warnings.simplefilter("error")
result = model_to_dict(model)
assert "foo" in result
Fixes deprecation warning in Pydantic 2.11+ where accessing model_fields on an instance is deprecated. Changed to use type(model).model_fields in model_to_dict().
Closes #652
Changes
How I tested this
Notes
Checklist