Skip to content

Commit

Permalink
Fix serialization in Color class
Browse files Browse the repository at this point in the history
Signed-off-by: ReRubis <[email protected]>
  • Loading branch information
ReRubis committed Dec 31, 2023
1 parent 07b4aa7 commit 99a3a09
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 28 deletions.
67 changes: 41 additions & 26 deletions asyncord/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,30 +59,6 @@ def to_hex(self) -> str:
"""Return the hexadecimal code of the color."""
return hex(self.value)

@classmethod
def validate(cls, value: int | str | RGB | tuple[int, int, int] | Self) -> Self:
"""Pydantic auxiliary validation method.
Args:
value: Value to validate.
Returns:
Validated Color.
Raises:
ValueError: If value is not
"""
if isinstance(value, int | str | RGB):
return cls.build(value)

if isinstance(value, tuple) and len(value) == 3 and all(isinstance(v, int) for v in value):
return cls.build(value)

if isinstance(value, cls):
return value

raise ValueError('Invalid value type')

@classmethod
def __get_pydantic_core_schema__(
cls, _source: type[BaseModel], _handler: Callable[[Any], CoreSchema],
Expand All @@ -107,9 +83,12 @@ def __get_pydantic_core_schema__(
])

return core_schema.no_info_after_validator_function(
function=cls.validate,
function=cls._validate,
schema=schema,
serialization=core_schema.simple_ser_schema('int'),
serialization=core_schema.plain_serializer_function_ser_schema(
function=cls._serialize,
when_used='json-unless-none',
),
)

def __repr__(self) -> str:
Expand All @@ -130,6 +109,42 @@ def __int__(self) -> int:
"""Return the integer value of the color."""
return self.value

@classmethod
def _validate(cls, value: int | str | RGB | tuple[int, int, int] | Self) -> Self:
"""Pydantic auxiliary validation method.
Args:
value: Value to validate.
Returns:
Validated Color.
Raises:
ValueError: If value is not
"""
if isinstance(value, int | str | RGB):
return cls.build(value)

if isinstance(value, tuple) and len(value) == 3 and all(isinstance(v, int) for v in value):
return cls.build(value)

if isinstance(value, cls):
return value

raise ValueError('Invalid value type')

@classmethod
def _serialize(cls, value: Self) -> int:
"""Pydantic auxiliary method to serialize the color.
Args:
value: Value to serialize.
Returns:
Serialized value.
"""
return int(value)


ColorInput = Annotated[int | str | RGB | tuple[int, int, int] | Color, Color]

Expand Down
4 changes: 2 additions & 2 deletions tests/test_color.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@ class TestModel(BaseModel):
assert isinstance(model.color, Color)
assert model.color == color

assert model.model_dump(mode='json') == f'{{"color": "{int(color)}"}}'
assert model.model_dump() == {'color': int(color)}
assert model.model_dump() == {'color': color}
assert model.model_dump(mode='json') == {'color': DECIMAL_VALUE}


def test_color_error_in_models():
Expand Down

0 comments on commit 99a3a09

Please sign in to comment.