Skip to content

Commit

Permalink
♻️ refactor some functions & minor changes
Browse files Browse the repository at this point in the history
  • Loading branch information
yezz123 committed Jun 2, 2024
1 parent 6dbc700 commit 791036a
Show file tree
Hide file tree
Showing 10 changed files with 41 additions and 60 deletions.
59 changes: 21 additions & 38 deletions pydantic_extra_types/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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:
"""
Expand Down Expand Up @@ -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:
"""
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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))
Expand Down
8 changes: 3 additions & 5 deletions pydantic_extra_types/coordinate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}'
Expand Down
4 changes: 2 additions & 2 deletions pydantic_extra_types/country.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions pydantic_extra_types/currency_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
2 changes: 1 addition & 1 deletion pydantic_extra_types/isbn.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def validate_isbn_format(value: str) -> None:
if isbn10_digit_calc(value) != value[-1]:
raise PydanticCustomError('isbn_invalid_digit_check_isbn10', 'Provided digit is invalid for given ISBN')

if isbn_length == 13:
elif isbn_length == 13:
if not value.isdigit():
raise PydanticCustomError('isbn13_invalid_characters', 'All digits of ISBN-13 must be integers')
if value[:3] not in ('978', '979'):
Expand Down
4 changes: 2 additions & 2 deletions pydantic_extra_types/language_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions pydantic_extra_types/pendulum_dt.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions pydantic_extra_types/phone_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down
4 changes: 2 additions & 2 deletions pydantic_extra_types/script_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
8 changes: 4 additions & 4 deletions pydantic_extra_types/ulid.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down Expand Up @@ -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)

0 comments on commit 791036a

Please sign in to comment.