def set(self, new_value): if self.type == 'color': try: color_val = Color(new_value) r, g, b = color_val.as_rgb_tuple(alpha=False) val = (r << 16) + (g << 8) + b except (ValueError, TypeError): return f'\u274c Invalid {self.description}. ' \ f'Use `{self.ctx.prefix}csettings {self.setting_key} reset` to reset it to {self.default}.' elif self.type == 'number': try: val = int(new_value) except (ValueError, TypeError): return f'\u274c Invalid {self.description}. ' \ f'Use `{self.ctx.prefix}csettings {self.setting_key} reset` to reset it to {self.default}.' elif self.type == 'boolean': try: val = get_positivity(new_value) except AttributeError: return f'\u274c Invalid {self.description}.' \ f'Use `{self.ctx.prefix}csettings {self.setting_key} false` to reset it.' else: log.warning(f"No setting type for {self.type} found") return try: setattr(self.character.options, self.setting_key, val) except ValidationError as e: return f"\u274c Invalid {self.description}: {e!s}.\n" \ f"Use `{self.ctx.prefix}csettings {self.setting_key} reset` to reset it to {self.default}." return f"\u2705 {self.description.capitalize()} set to {self.display_func(val)}.\n"
async def update_item(*, setColor: Color): return { "item color": setColor, "Name": setColor.as_named(), "Hex": setColor.as_hex(), "RGB": setColor.as_rgb_tuple() }
def to_pil_color(color: Color) -> PILColorTuple: """ Convert a pydantic Color to a PIL color 4-tuple Color.as_rgb_tuple() _almost_ works, but it returns the alpha channel as a float between 0 and 1, and PIL expects an int 0-255 """ # cast() business is a mypy workaround for # https://github.com/python/mypy/issues/1178 c = color.as_rgb_tuple() if len(c) == 3: return cast(Tuple[int, int, int], c) else: r, g, b, a = cast(Tuple[int, int, int, float], c) return r, g, b, round(a * 255)
def test_color_success(raw_color, as_tuple): c = Color(raw_color) assert c.as_rgb_tuple() == as_tuple assert c.original() == raw_color
from pydantic import BaseModel, ValidationError from pydantic.color import Color c = Color('ff00ff') print(c.as_named()) print(c.as_hex()) c2 = Color('green') print(c2.as_rgb_tuple()) print(c2.original()) print(repr(Color('hsl(180, 100%, 50%)'))) class Model(BaseModel): color: Color print(Model(color='purple')) try: Model(color='hello') except ValidationError as e: print(e)