pydantic / pydantic-extra-types

Extra Pydantic types.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Refactor exception handling in color lookup to use conditional check

maxsos opened this issue · comments

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:

  • Enhances code readability by removing the exception handling for a simple key lookup.
  • Clearly separates the logic for handling the presence and absence of the key in the dictionary.

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!

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.