Skip to content

Instantly share code, notes, and snippets.

@laundmo
Last active October 19, 2023 08:13
Show Gist options
  • Save laundmo/909707aa63f8842737af6e7de8f81d0d to your computer and use it in GitHub Desktop.
Save laundmo/909707aa63f8842737af6e7de8f81d0d to your computer and use it in GitHub Desktop.
Pydantic: ChainMap as a custom type
"""
Copyright 2023 laundmo
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Original Source: https://gist.github.com/laundmo/909707aa63f8842737af6e7de8f81d0d
"""
from collections import ChainMap as ChainMapBase
from typing import (
Any,
Dict,
Generic,
List,
TypeVar,
)
from pydantic import GetJsonSchemaHandler
from pydantic._internal._annotated_handlers import GetCoreSchemaHandler
from pydantic.json_schema import JsonSchemaValue
from pydantic_core import core_schema
from typing_extensions import get_args
_VT = TypeVar("_VT")
_KT = TypeVar("_KT")
class ChainMap(ChainMapBase[_KT, _VT], Generic[_KT, _VT]):
def __repr__(self):
return super().__repr__()
@classmethod
def __get_pydantic_core_schema__(
cls, source: Any, handler: GetCoreSchemaHandler
) -> core_schema.CoreSchema:
instance_schema = core_schema.is_instance_schema(cls)
# get type args of this class:
# get_args(ChainMap[str, int]) -> (str, int)
args = get_args(source)
if not args or len(args) != 2:
raise ValueError(
"ChainMap requires exactly 2 generics.\n\t-> Specify the type as"
" ChainMap[KeyT, ValueT]"
)
# replace the type and rely on Pydantic to generate the right schema
sequence_t_schema = handler.generate_schema(List[Dict[args[0], args[1]]]) # type: ignore
non_instance_schema = core_schema.with_info_after_validator_function(
lambda v, i: ChainMap(*v), sequence_t_schema
)
python_schema = core_schema.union_schema([instance_schema, non_instance_schema])
return core_schema.json_or_python_schema(
json_schema=core_schema.chain_schema(
[
core_schema.list_schema(
core_schema.dict_schema(
keys_schema=handler.generate_schema(args[0]),
values_schema=handler.generate_schema(args[1]),
),
),
python_schema,
]
),
python_schema=python_schema,
serialization=core_schema.plain_serializer_function_ser_schema(
lambda instance: instance.maps
),
)
@classmethod
def __get_pydantic_json_schema__(
cls, _core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue:
# Use the same schema that would be used for `int`
return handler(_core_schema)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment