Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: add support for pydantic 2.x #3282

Merged
merged 6 commits into from
Aug 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion requirements/base.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ jsonschema<5,>=3.2 # TODO: evaluate risk of removing jsonschema 3.x support
typing_extensions>=4.4,<5 # 3.7 doesn't have Literal

# resource validation & schema generation
pydantic~=1.8
pydantic>=1.8,<3
8 changes: 8 additions & 0 deletions samtranslator/compat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
try:
from pydantic import v1 as pydantic
ssenchenko marked this conversation as resolved.
Show resolved Hide resolved
except ImportError:
# Unfortunately mypy cannot handle this try/expect pattern, and "type: ignore"
# is the simplest work-around. See: https://github.com/python/mypy/issues/1153
import pydantic # type: ignore

__all__ = ["pydantic"]
3 changes: 1 addition & 2 deletions samtranslator/internal/schema_source/any_cfn_resource.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import pydantic

from samtranslator.compat import pydantic
from samtranslator.internal.schema_source.common import LenientBaseModel

constr = pydantic.constr
Expand Down
9 changes: 4 additions & 5 deletions samtranslator/internal/schema_source/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@
from pathlib import Path
from typing import Any, Dict, List, Optional, TypeVar, Union

import pydantic
from pydantic import Extra, Field
from typing_extensions import Literal

from samtranslator.compat import pydantic
from samtranslator.model.types import PassThrough


Expand Down Expand Up @@ -53,7 +52,7 @@ def passthrough_prop(sam_docs_stem: str, sam_docs_name: str, prop_path: List[str
for s in prop_path[1:]:
path.extend(["properties", s])
docs = _DOCS["properties"][sam_docs_stem][sam_docs_name]
return Field(
return pydantic.Field(
title=sam_docs_name,
# We add a custom value to the schema containing the path to the pass-through
# documentation; the dict containing the value is replaced in the final schema
Expand All @@ -68,7 +67,7 @@ def passthrough_prop(sam_docs_stem: str, sam_docs_name: str, prop_path: List[str

def _get_prop(stem: str, name: str) -> Any:
docs = _DOCS["properties"][stem][name]
return Field(
return pydantic.Field(
title=name,
# https://code.visualstudio.com/docs/languages/json#_use-rich-formatting-in-hovers
markdownDescription=docs,
Expand All @@ -78,7 +77,7 @@ def _get_prop(stem: str, name: str) -> Any:
# By default strict: https://pydantic-docs.helpmanual.io/usage/model_config/#change-behaviour-globally
class BaseModel(LenientBaseModel):
class Config:
extra = Extra.forbid
extra = pydantic.Extra.forbid

def __getattribute__(self, __name: str) -> Any:
"""Overloading get attribute operation to allow access PassThroughProp without using __root__"""
Expand Down
3 changes: 1 addition & 2 deletions samtranslator/internal/schema_source/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Type, Union

import pydantic

from samtranslator.compat import pydantic
from samtranslator.internal.schema_source import (
any_cfn_resource,
aws_serverless_api,
Expand Down
8 changes: 3 additions & 5 deletions samtranslator/model/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@
from contextlib import suppress
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, TypeVar

from pydantic import BaseModel
from pydantic.error_wrappers import ValidationError

from samtranslator.compat import pydantic
from samtranslator.model.exceptions import (
ExpectedType,
InvalidResourceException,
Expand All @@ -17,7 +15,7 @@
from samtranslator.model.types import IS_DICT, IS_STR, PassThrough, Validator, any_type, is_type
from samtranslator.plugins import LifeCycleEvents

RT = TypeVar("RT", bound=BaseModel) # return type
RT = TypeVar("RT", bound=pydantic.BaseModel) # return type


class PropertyType:
Expand Down Expand Up @@ -348,7 +346,7 @@ def validate_properties_and_return_model(self, cls: Type[RT]) -> RT:
"""
try:
return cls.parse_obj(self._generate_resource_dict()["Properties"])
except ValidationError as e:
except pydantic.error_wrappers.ValidationError as e:
error_properties: str = ""
with suppress(KeyError):
error_properties = ".".join(str(x) for x in e.errors()[0]["loc"])
Expand Down