[REF-3266] Check for pydantic v1 outside of try/except (#3643)

If pydantic v1 is already installed, there is no reason to restore the original
pydantic modules, which seems to introduce subtle incompatibilities with some
pydantic versions.

Perform the pydantic version check early on and exit for v1 before doing
anything with the sys.modules.

Fix #3642
This commit is contained in:
Masen Furer 2024-07-10 12:28:39 -07:00 committed by GitHub
parent 4c61838608
commit 1cfc811506
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -32,6 +32,13 @@ def pydantic_v1_patch():
Yields:
None when the Pydantic module is patched.
"""
import pydantic
if pydantic.__version__.startswith("1."):
# pydantic v1 is already installed
yield
return
patched_modules = [
"pydantic",
"pydantic.fields",
@ -42,11 +49,6 @@ def pydantic_v1_patch():
try:
import pydantic.v1 # type: ignore
if pydantic.__version__.startswith("1."):
# pydantic v1 is already installed
yield
return
sys.modules["pydantic.fields"] = pydantic.v1.fields # type: ignore
sys.modules["pydantic.main"] = pydantic.v1.main # type: ignore
sys.modules["pydantic.errors"] = pydantic.v1.errors # type: ignore