Skip to content

Commit d7b0e4a

Browse files
authored
Add long and short format to as_hex (#93)
* Add long and short format to as_hex * Satisfy pre-commit * Add 3.7 compatibility * Skip coverage for python3.7 compat * Check for python version * Skip coverage for both imports
1 parent 092251d commit d7b0e4a

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

pydantic_extra_types/color.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,15 @@
1111

1212
import math
1313
import re
14+
import sys
1415
from colorsys import hls_to_rgb, rgb_to_hls
1516
from typing import Any, Callable, Tuple, Union, cast
1617

18+
if sys.version_info >= (3, 8): # pragma: no cover
19+
from typing import Literal
20+
else: # pragma: no cover
21+
from typing_extensions import Literal
22+
1723
from pydantic import GetJsonSchemaHandler
1824
from pydantic._internal import _repr
1925
from pydantic.json_schema import JsonSchemaValue
@@ -132,7 +138,7 @@ def as_named(self, *, fallback: bool = False) -> str:
132138
else:
133139
return self.as_hex()
134140

135-
def as_hex(self) -> str:
141+
def as_hex(self, format: Literal['short', 'long'] = 'short') -> str:
136142
"""Returns the hexadecimal representation of the color.
137143
138144
Hex string representing the color can be 3, 4, 6, or 8 characters depending on whether the string
@@ -146,7 +152,7 @@ def as_hex(self) -> str:
146152
values.append(float_to_255(self._rgba.alpha))
147153

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

tests/test_types_color.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,14 @@ def test_as_hex():
186186
assert Color((1, 2, 3, 0.1)).as_hex() == '#0102031a'
187187

188188

189+
def test_as_hex_long():
190+
assert Color((1, 2, 3)).as_hex(format='long') == '#010203'
191+
assert Color((119, 119, 119)).as_hex(format='long') == '#777777'
192+
assert Color((119, 0, 238)).as_hex(format='long') == '#7700ee'
193+
assert Color('B0B').as_hex(format='long') == '#bb00bb'
194+
assert Color('#0102031a').as_hex(format='long') == '#0102031a'
195+
196+
189197
def test_as_named():
190198
assert Color((0, 255, 255)).as_named() == 'cyan'
191199
assert Color('#808000').as_named() == 'olive'

0 commit comments

Comments
 (0)