pydantic / pydantic-extra-types

Extra Pydantic types.
MIT License
176 stars 47 forks source link

Refactor exception handling in color lookup to use conditional check #181

Closed maxsos closed 2 months ago

maxsos commented 3 months ago

Description:

Current Implementation: https://github.com/pydantic/pydantic-extra-types/blob/main/pydantic_extra_types/color.py#L109

The current code uses a try-except block to handle a potential KeyError when looking up a color value in the COLORS_BY_VALUE dictionary:

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

Proposed Change: Refactor the code to use an if-else conditional check instead of a try-except block. This change improves code readability and leverages a more predictable conditional flow:

if rgb in COLORS_BY_VALUE:
    return COLORS_BY_VALUE[rgb]
else:
    if fallback:
        return self.as_hex()
    else:
        raise ValueError('no named color found, use fallback=True, as_hex() or as_rgb()')

Benefits:

Impact: This change is expected to maintain the existing functionality while improving code clarity.

Please let me know if there are any specific tests or cases you would like me to address in this refactoring.

Thank you!

yezz123 commented 2 months ago

Hey @maxsos Sorry for the late response 🙏🏻

Feel free to open a PR, and we can discuss the potential behavior changes and any specific tests or cases that need to be addressed.

yezz123 commented 2 months ago

fixed #192