diff --git a/pydantic_extra_types/color.py b/pydantic_extra_types/color.py index 8b9eabea..8e28ff4a 100644 --- a/pydantic_extra_types/color.py +++ b/pydantic_extra_types/color.py @@ -121,17 +121,16 @@ def as_named(self, *, fallback: bool = False) -> str: Raises: ValueError: When no named color is found and fallback is `False`. """ - if self._rgba.alpha is None: - rgb = cast(Tuple[int, int, int], self.as_rgb_tuple()) - try: - return COLORS_BY_VALUE[rgb] - except KeyError as e: - if fallback: - return self.as_hex() - else: - raise ValueError('no named color found, use fallback=True, as_hex() or as_rgb()') from e - else: + if self._rgba.alpha is not None: return self.as_hex() + rgb = cast(Tuple[int, int, int], self.as_rgb_tuple()) + try: + return COLORS_BY_VALUE[rgb] + except KeyError as e: + if fallback: + return self.as_hex() + else: + raise ValueError('no named color found, use fallback=True, as_hex() or as_rgb()') from e def as_hex(self, format: Literal['short', 'long'] = 'short') -> str: """Returns the hexadecimal representation of the color. @@ -149,7 +148,7 @@ def as_hex(self, format: Literal['short', 'long'] = 'short') -> str: as_hex = ''.join(f'{v:02x}' for v 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 + return f'#{as_hex}' def as_rgb(self) -> str: """ @@ -179,16 +178,10 @@ def as_rgb_tuple(self, *, alpha: bool | None = None) -> ColorTuple: If alpha is included, it is in the range 0 to 1. """ r, g, b = (float_to_255(c) for c in self._rgba[:3]) - if alpha is None: - if self._rgba.alpha is None: - return r, g, b - else: - return r, g, b, self._alpha_float() - elif alpha: - return r, g, b, self._alpha_float() - else: - # alpha is False + if alpha is None and self._rgba.alpha is None or alpha is not None and not alpha: return r, g, b + else: + return r, g, b, self._alpha_float() def as_hsl(self) -> str: """ @@ -225,11 +218,7 @@ def as_hsl_tuple(self, *, alpha: bool | None = None) -> HslColorTuple: return h, s, l else: return h, s, l, self._alpha_float() - if alpha: - return h, s, l, self._alpha_float() - else: - # alpha is False - return h, s, l + return (h, s, l, self._alpha_float()) if alpha else (h, s, l) def _alpha_float(self) -> float: return 1 if self._rgba.alpha is None else self._rgba.alpha @@ -315,20 +304,14 @@ def parse_str(value: str) -> RGBA: if m: *rgb, a = m.groups() r, g, b = (int(v * 2, 16) for v in rgb) - if a: - alpha: float | None = int(a * 2, 16) / 255 - else: - alpha = None + alpha = int(a * 2, 16) / 255 if a else None return ints_to_rgba(r, g, b, alpha) m = re.fullmatch(r_hex_long, value_lower) if m: *rgb, a = m.groups() r, g, b = (int(v, 16) for v in rgb) - if a: - alpha = int(a, 16) / 255 - else: - alpha = None + alpha = int(a, 16) / 255 if a else None return ints_to_rgba(r, g, b, alpha) 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: """ try: color = float(value) - except ValueError: + except ValueError as e: raise PydanticCustomError( 'color_error', 'value is not a valid color: color values must be a valid number', - ) + ) from e if 0 <= color <= max_val: return color / max_val else: @@ -425,11 +408,11 @@ def parse_float_alpha(value: None | str | float | int) -> float | None: alpha = float(value[:-1]) / 100 else: alpha = float(value) - except ValueError: + except ValueError as e: raise PydanticCustomError( 'color_error', 'value is not a valid color: alpha values must be a valid float', - ) + ) from e if math.isclose(alpha, 1): return None @@ -465,7 +448,7 @@ def parse_hsl(h: str, h_units: str, sat: str, light: str, alpha: float | None = h_value = h_value % rads / rads else: # turns - h_value = h_value % 1 + h_value %= 1 r, g, b = hls_to_rgb(h_value, l_value, s_value) return RGBA(r, g, b, parse_float_alpha(alpha)) diff --git a/pydantic_extra_types/coordinate.py b/pydantic_extra_types/coordinate.py index 10eaa054..29d58927 100644 --- a/pydantic_extra_types/coordinate.py +++ b/pydantic_extra_types/coordinate.py @@ -123,18 +123,16 @@ def _parse_str(cls, value: Any, handler: core_schema.ValidatorFunctionWrapHandle return value try: value = tuple(float(x) for x in value.split(',')) - except ValueError: + except ValueError as e: raise PydanticCustomError( 'coordinate_error', 'value is not a valid coordinate: string is not recognized as a valid coordinate', - ) + ) from e return ArgsKwargs(args=value) @classmethod def _parse_tuple(cls, value: Any, handler: core_schema.ValidatorFunctionWrapHandler) -> Any: - if not isinstance(value, tuple): - return value - return ArgsKwargs(args=handler(value)) + return ArgsKwargs(args=handler(value)) if isinstance(value, tuple) else value def __str__(self) -> str: return f'{self.latitude},{self.longitude}' diff --git a/pydantic_extra_types/country.py b/pydantic_extra_types/country.py index 7af99c74..c449b346 100644 --- a/pydantic_extra_types/country.py +++ b/pydantic_extra_types/country.py @@ -13,10 +13,10 @@ try: import pycountry -except ModuleNotFoundError: # pragma: no cover +except ModuleNotFoundError as e: # pragma: no cover raise RuntimeError( 'The `country` module requires "pycountry" to be installed. You can install it with "pip install pycountry".' - ) + ) from e @dataclass diff --git a/pydantic_extra_types/currency_code.py b/pydantic_extra_types/currency_code.py index fbc0cbd3..3c8e0a18 100644 --- a/pydantic_extra_types/currency_code.py +++ b/pydantic_extra_types/currency_code.py @@ -11,11 +11,11 @@ try: import pycountry -except ModuleNotFoundError: # pragma: no cover +except ModuleNotFoundError as e: # pragma: no cover raise RuntimeError( 'The `currency_code` module requires "pycountry" to be installed. You can install it with "pip install ' 'pycountry".' - ) + ) from e # List of codes that should not be usually used within regular transactions _CODES_FOR_BONDS_METAL_TESTING = { diff --git a/pydantic_extra_types/language_code.py b/pydantic_extra_types/language_code.py index 8c153856..fb033b82 100644 --- a/pydantic_extra_types/language_code.py +++ b/pydantic_extra_types/language_code.py @@ -13,11 +13,11 @@ try: import pycountry -except ModuleNotFoundError: # pragma: no cover +except ModuleNotFoundError as e: # pragma: no cover raise RuntimeError( 'The `language_code` module requires "pycountry" to be installed.' ' You can install it with "pip install pycountry".' - ) + ) from e @dataclass diff --git a/pydantic_extra_types/pendulum_dt.py b/pydantic_extra_types/pendulum_dt.py index d5e2b96e..633b02db 100644 --- a/pydantic_extra_types/pendulum_dt.py +++ b/pydantic_extra_types/pendulum_dt.py @@ -10,10 +10,10 @@ from pendulum import DateTime as _DateTime from pendulum import Duration as _Duration from pendulum import parse -except ModuleNotFoundError: # pragma: no cover +except ModuleNotFoundError as e: # pragma: no cover raise RuntimeError( 'The `pendulum_dt` module requires "pendulum" to be installed. You can install it with "pip install pendulum".' - ) + ) from e from datetime import date, datetime, timedelta from typing import Any, List, Type diff --git a/pydantic_extra_types/phone_numbers.py b/pydantic_extra_types/phone_numbers.py index e9dcb9a1..1fb96782 100644 --- a/pydantic_extra_types/phone_numbers.py +++ b/pydantic_extra_types/phone_numbers.py @@ -14,10 +14,10 @@ try: import phonenumbers -except ModuleNotFoundError: # pragma: no cover +except ModuleNotFoundError as e: # pragma: no cover raise RuntimeError( '`PhoneNumber` requires "phonenumbers" to be installed. You can install it with "pip install phonenumbers"' - ) + ) from e GeneratorCallableStr = Generator[Callable[..., str], None, None] diff --git a/pydantic_extra_types/script_code.py b/pydantic_extra_types/script_code.py index 2cd82e98..eea44f02 100644 --- a/pydantic_extra_types/script_code.py +++ b/pydantic_extra_types/script_code.py @@ -11,11 +11,11 @@ try: import pycountry -except ModuleNotFoundError: # pragma: no cover +except ModuleNotFoundError as e: # pragma: no cover raise RuntimeError( 'The `script_code` module requires "pycountry" to be installed.' ' You can install it with "pip install pycountry".' - ) + ) from e class ISO_15924(str): diff --git a/pydantic_extra_types/ulid.py b/pydantic_extra_types/ulid.py index 5891f9f5..3173b4dc 100644 --- a/pydantic_extra_types/ulid.py +++ b/pydantic_extra_types/ulid.py @@ -15,10 +15,10 @@ try: from ulid import ULID as _ULID -except ModuleNotFoundError: # pragma: no cover +except ModuleNotFoundError as e: # pragma: no cover raise RuntimeError( 'The `ulid` module requires "python-ulid" to be installed. You can install it with "pip install python-ulid".' - ) + ) from e UlidType = Union[str, bytes, int] @@ -58,6 +58,6 @@ def _validate_ulid(cls, value: Any, handler: core_schema.ValidatorFunctionWrapHa ulid = value else: ulid = _ULID.from_bytes(value) - except ValueError: - raise PydanticCustomError('ulid_format', 'Unrecognized format') + except ValueError as e: + raise PydanticCustomError('ulid_format', 'Unrecognized format') from e return handler(ulid)