|
2 | 2 | from enum import Enum |
3 | 3 | from types import DynamicClassAttribute |
4 | 4 |
|
| 5 | +from pydantic import GetCoreSchemaHandler |
| 6 | +from pydantic_core import core_schema |
| 7 | +from pydantic_core import PydanticCustomError |
| 8 | + |
5 | 9 |
|
6 | 10 | class classproperty: # noqa |
7 | 11 | def __init__(self, getter): |
@@ -33,6 +37,47 @@ def value(self) -> int: |
33 | 37 | def __unicode__(self): |
34 | 38 | return self.__doc__ |
35 | 39 |
|
| 40 | + @classmethod |
| 41 | + def __get_pydantic_core_schema__(cls, source_type, handler: GetCoreSchemaHandler): |
| 42 | + """Customize Pydantic v2 validation to show titles in error messages.""" |
| 43 | + return core_schema.no_info_after_validator_function( |
| 44 | + cls._validate, |
| 45 | + core_schema.union_schema( |
| 46 | + [ |
| 47 | + core_schema.is_instance_schema(cls), |
| 48 | + core_schema.int_schema(), |
| 49 | + core_schema.str_schema(), |
| 50 | + ] |
| 51 | + ), |
| 52 | + serialization=core_schema.plain_serializer_function_ser_schema( |
| 53 | + lambda x: x.value if isinstance(x, cls) else x, when_used="json" |
| 54 | + ), |
| 55 | + ) |
| 56 | + |
| 57 | + @classmethod |
| 58 | + def _validate(cls, value): |
| 59 | + """Validate and convert value to enum member.""" |
| 60 | + if isinstance(value, cls): |
| 61 | + return value |
| 62 | + |
| 63 | + # Try to find by value |
| 64 | + if isinstance(value, int): |
| 65 | + for enum in cls: |
| 66 | + if enum.value == value: |
| 67 | + return enum |
| 68 | + |
| 69 | + # Try to find by title or name |
| 70 | + if isinstance(value, str): |
| 71 | + for enum in cls: |
| 72 | + if enum.__doc__ and enum.__doc__.lower() == value.lower(): |
| 73 | + return enum |
| 74 | + if value in cls.__members__: |
| 75 | + return cls.__members__[value] |
| 76 | + |
| 77 | + # Build error message with titles |
| 78 | + available = ", ".join(f"{enum.__doc__.lower()}" for enum in cls if enum.__doc__) |
| 79 | + raise PydanticCustomError("enum", f"Input should be: {available}") |
| 80 | + |
36 | 81 | @classmethod |
37 | 82 | def choices(cls) -> typing.Tuple[str]: |
38 | 83 | """Return all titles as choices.""" |
|
0 commit comments