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

Add long and short format to as_hex #93

Merged
merged 6 commits into from
Aug 30, 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
10 changes: 8 additions & 2 deletions pydantic_extra_types/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,15 @@

import math
import re
import sys
from colorsys import hls_to_rgb, rgb_to_hls
from typing import Any, Callable, Tuple, Union, cast

if sys.version_info >= (3, 8): # pragma: no cover
from typing import Literal
else: # pragma: no cover
from typing_extensions import Literal

from pydantic import GetJsonSchemaHandler
from pydantic._internal import _repr
from pydantic.json_schema import JsonSchemaValue
Expand Down Expand Up @@ -132,7 +138,7 @@ def as_named(self, *, fallback: bool = False) -> str:
else:
return self.as_hex()

def as_hex(self) -> str:
def as_hex(self, format: Literal['short', 'long'] = 'short') -> str:
"""Returns the hexadecimal representation of the color.

Hex string representing the color can be 3, 4, 6, or 8 characters depending on whether the string
Expand All @@ -146,7 +152,7 @@ def as_hex(self) -> str:
values.append(float_to_255(self._rgba.alpha))

as_hex = ''.join(f'{v:02x}' for v in values)
if all(c in repeat_colors for c in values):
if format == 'short' and all(c in repeat_colors for c in values):
as_hex = ''.join(as_hex[c] for c in range(0, len(as_hex), 2))
return '#' + as_hex

Expand Down
8 changes: 8 additions & 0 deletions tests/test_types_color.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,14 @@ def test_as_hex():
assert Color((1, 2, 3, 0.1)).as_hex() == '#0102031a'


def test_as_hex_long():
assert Color((1, 2, 3)).as_hex(format='long') == '#010203'
assert Color((119, 119, 119)).as_hex(format='long') == '#777777'
assert Color((119, 0, 238)).as_hex(format='long') == '#7700ee'
assert Color('B0B').as_hex(format='long') == '#bb00bb'
assert Color('#0102031a').as_hex(format='long') == '#0102031a'


def test_as_named():
assert Color((0, 255, 255)).as_named() == 'cyan'
assert Color('#808000').as_named() == 'olive'
Expand Down