Skip to content

Commit 76f4b48

Browse files
authored
♻️ refactor some functions & minor changes (#180)
1 parent d9b1e40 commit 76f4b48

File tree

9 files changed

+40
-59
lines changed

9 files changed

+40
-59
lines changed

pydantic_extra_types/color.py

Lines changed: 21 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -121,17 +121,16 @@ def as_named(self, *, fallback: bool = False) -> str:
121121
Raises:
122122
ValueError: When no named color is found and fallback is `False`.
123123
"""
124-
if self._rgba.alpha is None:
125-
rgb = cast(Tuple[int, int, int], self.as_rgb_tuple())
126-
try:
127-
return COLORS_BY_VALUE[rgb]
128-
except KeyError as e:
129-
if fallback:
130-
return self.as_hex()
131-
else:
132-
raise ValueError('no named color found, use fallback=True, as_hex() or as_rgb()') from e
133-
else:
124+
if self._rgba.alpha is not None:
134125
return self.as_hex()
126+
rgb = cast(Tuple[int, int, int], self.as_rgb_tuple())
127+
try:
128+
return COLORS_BY_VALUE[rgb]
129+
except KeyError as e:
130+
if fallback:
131+
return self.as_hex()
132+
else:
133+
raise ValueError('no named color found, use fallback=True, as_hex() or as_rgb()') from e
135134

136135
def as_hex(self, format: Literal['short', 'long'] = 'short') -> str:
137136
"""Returns the hexadecimal representation of the color.
@@ -149,7 +148,7 @@ def as_hex(self, format: Literal['short', 'long'] = 'short') -> str:
149148
as_hex = ''.join(f'{v:02x}' for v in values)
150149
if format == 'short' and all(c in repeat_colors for c in values):
151150
as_hex = ''.join(as_hex[c] for c in range(0, len(as_hex), 2))
152-
return '#' + as_hex
151+
return f'#{as_hex}'
153152

154153
def as_rgb(self) -> str:
155154
"""
@@ -179,16 +178,10 @@ def as_rgb_tuple(self, *, alpha: bool | None = None) -> ColorTuple:
179178
If alpha is included, it is in the range 0 to 1.
180179
"""
181180
r, g, b = (float_to_255(c) for c in self._rgba[:3])
182-
if alpha is None:
183-
if self._rgba.alpha is None:
184-
return r, g, b
185-
else:
186-
return r, g, b, self._alpha_float()
187-
elif alpha:
188-
return r, g, b, self._alpha_float()
189-
else:
190-
# alpha is False
181+
if alpha is None and self._rgba.alpha is None or alpha is not None and not alpha:
191182
return r, g, b
183+
else:
184+
return r, g, b, self._alpha_float()
192185

193186
def as_hsl(self) -> str:
194187
"""
@@ -225,11 +218,7 @@ def as_hsl_tuple(self, *, alpha: bool | None = None) -> HslColorTuple:
225218
return h, s, l
226219
else:
227220
return h, s, l, self._alpha_float()
228-
if alpha:
229-
return h, s, l, self._alpha_float()
230-
else:
231-
# alpha is False
232-
return h, s, l
221+
return (h, s, l, self._alpha_float()) if alpha else (h, s, l)
233222

234223
def _alpha_float(self) -> float:
235224
return 1 if self._rgba.alpha is None else self._rgba.alpha
@@ -315,20 +304,14 @@ def parse_str(value: str) -> RGBA:
315304
if m:
316305
*rgb, a = m.groups()
317306
r, g, b = (int(v * 2, 16) for v in rgb)
318-
if a:
319-
alpha: float | None = int(a * 2, 16) / 255
320-
else:
321-
alpha = None
307+
alpha = int(a * 2, 16) / 255 if a else None
322308
return ints_to_rgba(r, g, b, alpha)
323309

324310
m = re.fullmatch(r_hex_long, value_lower)
325311
if m:
326312
*rgb, a = m.groups()
327313
r, g, b = (int(v, 16) for v in rgb)
328-
if a:
329-
alpha = int(a, 16) / 255
330-
else:
331-
alpha = None
314+
alpha = int(a, 16) / 255 if a else None
332315
return ints_to_rgba(r, g, b, alpha)
333316

334317
m = re.fullmatch(r_rgb, value_lower) or re.fullmatch(r_rgb_v4_style, value_lower)
@@ -390,11 +373,11 @@ def parse_color_value(value: int | str, max_val: int = 255) -> float:
390373
"""
391374
try:
392375
color = float(value)
393-
except ValueError:
376+
except ValueError as e:
394377
raise PydanticCustomError(
395378
'color_error',
396379
'value is not a valid color: color values must be a valid number',
397-
)
380+
) from e
398381
if 0 <= color <= max_val:
399382
return color / max_val
400383
else:
@@ -425,11 +408,11 @@ def parse_float_alpha(value: None | str | float | int) -> float | None:
425408
alpha = float(value[:-1]) / 100
426409
else:
427410
alpha = float(value)
428-
except ValueError:
411+
except ValueError as e:
429412
raise PydanticCustomError(
430413
'color_error',
431414
'value is not a valid color: alpha values must be a valid float',
432-
)
415+
) from e
433416

434417
if math.isclose(alpha, 1):
435418
return None
@@ -465,7 +448,7 @@ def parse_hsl(h: str, h_units: str, sat: str, light: str, alpha: float | None =
465448
h_value = h_value % rads / rads
466449
else:
467450
# turns
468-
h_value = h_value % 1
451+
h_value %= 1
469452

470453
r, g, b = hls_to_rgb(h_value, l_value, s_value)
471454
return RGBA(r, g, b, parse_float_alpha(alpha))

pydantic_extra_types/coordinate.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -123,18 +123,16 @@ def _parse_str(cls, value: Any, handler: core_schema.ValidatorFunctionWrapHandle
123123
return value
124124
try:
125125
value = tuple(float(x) for x in value.split(','))
126-
except ValueError:
126+
except ValueError as e:
127127
raise PydanticCustomError(
128128
'coordinate_error',
129129
'value is not a valid coordinate: string is not recognized as a valid coordinate',
130-
)
130+
) from e
131131
return ArgsKwargs(args=value)
132132

133133
@classmethod
134134
def _parse_tuple(cls, value: Any, handler: core_schema.ValidatorFunctionWrapHandler) -> Any:
135-
if not isinstance(value, tuple):
136-
return value
137-
return ArgsKwargs(args=handler(value))
135+
return ArgsKwargs(args=handler(value)) if isinstance(value, tuple) else value
138136

139137
def __str__(self) -> str:
140138
return f'{self.latitude},{self.longitude}'

pydantic_extra_types/country.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@
1313

1414
try:
1515
import pycountry
16-
except ModuleNotFoundError: # pragma: no cover
16+
except ModuleNotFoundError as e: # pragma: no cover
1717
raise RuntimeError(
1818
'The `country` module requires "pycountry" to be installed. You can install it with "pip install pycountry".'
19-
)
19+
) from e
2020

2121

2222
@dataclass

pydantic_extra_types/currency_code.py

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

1212
try:
1313
import pycountry
14-
except ModuleNotFoundError: # pragma: no cover
14+
except ModuleNotFoundError as e: # pragma: no cover
1515
raise RuntimeError(
1616
'The `currency_code` module requires "pycountry" to be installed. You can install it with "pip install '
1717
'pycountry".'
18-
)
18+
) from e
1919

2020
# List of codes that should not be usually used within regular transactions
2121
_CODES_FOR_BONDS_METAL_TESTING = {

pydantic_extra_types/language_code.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,11 @@
1313

1414
try:
1515
import pycountry
16-
except ModuleNotFoundError: # pragma: no cover
16+
except ModuleNotFoundError as e: # pragma: no cover
1717
raise RuntimeError(
1818
'The `language_code` module requires "pycountry" to be installed.'
1919
' You can install it with "pip install pycountry".'
20-
)
20+
) from e
2121

2222

2323
@dataclass

pydantic_extra_types/pendulum_dt.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@
1010
from pendulum import DateTime as _DateTime
1111
from pendulum import Duration as _Duration
1212
from pendulum import parse
13-
except ModuleNotFoundError: # pragma: no cover
13+
except ModuleNotFoundError as e: # pragma: no cover
1414
raise RuntimeError(
1515
'The `pendulum_dt` module requires "pendulum" to be installed. You can install it with "pip install pendulum".'
16-
)
16+
) from e
1717
from datetime import date, datetime, timedelta
1818
from typing import Any, List, Type
1919

pydantic_extra_types/phone_numbers.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@
1414

1515
try:
1616
import phonenumbers
17-
except ModuleNotFoundError: # pragma: no cover
17+
except ModuleNotFoundError as e: # pragma: no cover
1818
raise RuntimeError(
1919
'`PhoneNumber` requires "phonenumbers" to be installed. You can install it with "pip install phonenumbers"'
20-
)
20+
) from e
2121

2222
GeneratorCallableStr = Generator[Callable[..., str], None, None]
2323

pydantic_extra_types/script_code.py

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

1212
try:
1313
import pycountry
14-
except ModuleNotFoundError: # pragma: no cover
14+
except ModuleNotFoundError as e: # pragma: no cover
1515
raise RuntimeError(
1616
'The `script_code` module requires "pycountry" to be installed.'
1717
' You can install it with "pip install pycountry".'
18-
)
18+
) from e
1919

2020

2121
class ISO_15924(str):

pydantic_extra_types/ulid.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@
1515

1616
try:
1717
from ulid import ULID as _ULID
18-
except ModuleNotFoundError: # pragma: no cover
18+
except ModuleNotFoundError as e: # pragma: no cover
1919
raise RuntimeError(
2020
'The `ulid` module requires "python-ulid" to be installed. You can install it with "pip install python-ulid".'
21-
)
21+
) from e
2222

2323
UlidType = Union[str, bytes, int]
2424

@@ -58,6 +58,6 @@ def _validate_ulid(cls, value: Any, handler: core_schema.ValidatorFunctionWrapHa
5858
ulid = value
5959
else:
6060
ulid = _ULID.from_bytes(value)
61-
except ValueError:
62-
raise PydanticCustomError('ulid_format', 'Unrecognized format')
61+
except ValueError as e:
62+
raise PydanticCustomError('ulid_format', 'Unrecognized format') from e
6363
return handler(ulid)

0 commit comments

Comments
 (0)