|
| 1 | +from typing import Optional |
| 2 | + |
| 3 | + |
| 4 | +def pydantic_import(class_name, sub_module_path: Optional[str] = None): |
| 5 | + import importlib |
| 6 | + import pkg_resources |
| 7 | + |
| 8 | + # Get the version of pydantic |
| 9 | + pydantic_version = pkg_resources.get_distribution("pydantic").version |
| 10 | + |
| 11 | + # Check if the version is 1 |
| 12 | + if pydantic_version.startswith("1"): |
| 13 | + pydantic_v1_module_name = "pydantic" if sub_module_path is None else f"pydantic.{sub_module_path}" |
| 14 | + klass = getattr(importlib.import_module("pydantic"), class_name) |
| 15 | + else: # use pydantic 2 v1 thunk |
| 16 | + pydantic_v1_module_name = "pydantic.v1" if sub_module_path is None else f"pydantic.{sub_module_path}" |
| 17 | + |
| 18 | + klass = getattr(importlib.import_module(pydantic_v1_module_name), class_name) |
| 19 | + |
| 20 | + return klass |
| 21 | + |
| 22 | + |
| 23 | +BaseModel = pydantic_import("BaseModel") |
| 24 | +PrivateAttr = pydantic_import("PrivateAttr") |
| 25 | +Field = pydantic_import("Field") |
| 26 | +ModelField = pydantic_import("ModelField", "fields") |
| 27 | +ValidationError = pydantic_import("ValidationError") |
| 28 | +ErrorWrapper = pydantic_import("ErrorWrapper", "error_wrappers") |
| 29 | + |
| 30 | +validator = pydantic_import("validator") |
| 31 | +root_validator = pydantic_import("root_validator") |
| 32 | +conint = pydantic_import("conint") |
| 33 | +conlist = pydantic_import("conlist") |
| 34 | +constr = pydantic_import("constr") |
| 35 | +confloat = pydantic_import("confloat") |
0 commit comments