Reputation: 33
I have a class called bit that codes for an svg rectangle. The class is instantiated with a variable saying what color the svg rectangle should be. I want it to accept colors in four styles. hex, rgb percent triplet, rgb integer triplet, and named. The init function then converts the color value to hex. I've got it working but it relies on a nested try except block and the exceptions thrown by the webcolors module. If one conversion fails it tries the next, and so on until it either succeeds or raises a final exception.
import svgwrite
from webcolors import name_to_hex, normalize_integer_triplet, rgb_percent_to_hex, normalize_hex, normalize_percent_triplet, rgb_to_hex
dwg = svgwrite.Drawing('qr.svg')
class Bit:
def __init__(self, bit_color:str, spec:str='css3'):
self.bit_type=1
self.spec=spec
try:
self.bit_color=name_to_hex(bit_color,spec)
except (ValueError, AttributeError):
try:
self.bit_color=rgb_to_hex(normalize_integer_triplet(bit_color))
except (ValueError, TypeError):
try:
self.bit_color=rgb_percent_to_hex(normalize_percent_triplet(bit_color))
except ValueError:
try:
self.bit_color=normalize_hex(bit_color)
except ValueError:
raise ValueError('Color not recognized!')
While this works and lets the user enter a color in the most common ways, it looks pretty ugly to me. Is there a way to refactor this?
Upvotes: 0
Views: 139
Reputation: 71454
One possibility:
try:
self.bit_color=name_to_hex(bit_color, spec)
return
except (ValueError, AttributeError):
pass
try:
self.bit_color=rgb_to_hex(normalize_integer_triplet(bit_color))
return
except (ValueError, TypeError):
pass
try:
self.bit_color=rgb_percent_to_hex(normalize_percent_triplet(bit_color))
return
except ValueError:
pass
try:
self.bit_color=normalize_hex(bit_color)
except ValueError:
raise ValueError('Color not recognized!')
Upvotes: 1