👽️ Update Color
import depending on the version of Pydantic
#14060
+8
−1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description:
Summary
This PR addresses the deprecation warning for
Color
in FastAPI when using Pydantic v2 while maintaining backward compatibility with Pydantic v1.Previously,
fastapi/encoders.py
importedColor
directly frompydantic.color
, which is deprecated in Pydantic v2, leading to warnings for users upgrading.This change ensures that the correct
Color
class is used depending on the installed Pydantic version.Changes
Color
:No other functionality is altered.
Fully backward-compatible with both Pydantic v1 and v2.
Checklist
I have verified that the change fixes the deprecation warning.
Code follows existing FastAPI style and conventions.
Tests pass for Pydantic v2.
Tests pass for Pydantic v1.
No breaking changes introduced for either Pydantic version.
Documentation updated if necessary (none needed for this fix).
Testing
Environment 1 – Pydantic v2 (current default)
pytest tests/test_jsonable_encoder.py -v
21 tests collected
18 passed, 3 skipped (v1-specific tests)
Environment 2 – Pydantic v1
pip install "pydantic<2.0"
pytest tests/test_jsonable_encoder.py -v
21 tests collected
17 passed, 4 skipped (v2-specific tests)
Results: ✅ All relevant tests pass in both environments. Only version-specific tests are skipped, as expected.
Motivation
Remove Pydantic v2 deprecation warnings.
Maintain backward compatibility with Pydantic v1.
Ensure smooth user experience for projects upgrading to Pydantic v2.