From c5ff727a6c60625e5afccf1d35e8950993a8b0be Mon Sep 17 00:00:00 2001 From: Talley Lambert Date: Tue, 10 Aug 2021 16:42:54 -0400 Subject: [PATCH] use pydantic Color type (#100) * use pydantic color * add int method --- src/ome_autogen.py | 33 +++++++++++++++++++++++++++++++++ src/ome_types/schema.py | 7 ++++--- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/src/ome_autogen.py b/src/ome_autogen.py index 6abe22f2..5ed8183d 100644 --- a/src/ome_autogen.py +++ b/src/ome_autogen.py @@ -521,6 +521,37 @@ def make_enum(component: XsdComponent) -> List[str]: return lines +def make_color() -> List[str]: + color = """ + from pydantic import color + class Color(color.Color): + def __init__(self, val: color.ColorType) -> None: + if isinstance(val, int): + val = self._int2tuple(val) + super().__init__(val) + + @classmethod + def _int2tuple(cls, val: int): + return (val >> 24 & 255, val >> 16 & 255, val >> 8 & 255, (val & 255) / 255) + + def as_int32(self) -> int: + r, g, b, *a = self.as_rgb_tuple() + v = r << 24 | g << 16 | b << 8 | int((a[0] if a else 1) * 255) + if v < 2 ** 32 // 2: + return v + return v - 2 ** 32 + + def __eq__(self, o: object) -> bool: + if isinstance(o, Color): + return self.as_int32() == o.as_int32() + return False + + def __int__(self) -> int: + return self.as_int32() + """ + return dedent(color).strip().splitlines() + + facet_converters = { qnames.XSD_PATTERN: lambda f: [f"regex = re.compile(r'{f.regexps[0]}')"], qnames.XSD_MIN_INCLUSIVE: lambda f: [f"ge = {f.value}"], @@ -888,6 +919,8 @@ def is_enum(self) -> bool: return is_enum def _simple_class(self) -> List[str]: + if self.type.local_name == "Color": + return make_color() if self.is_enum: return make_enum(self.elem) diff --git a/src/ome_types/schema.py b/src/ome_types/schema.py index b4f7f746..1460217d 100644 --- a/src/ome_types/schema.py +++ b/src/ome_types/schema.py @@ -23,6 +23,7 @@ _plural_to_singular, _singular_to_plural, _snake_to_camel, + simple_types, ) URI_OME = "http://www.openmicroscopy.org/Schemas/OME/2016-06" @@ -228,10 +229,10 @@ def element_encode( field.default_factory() if field.default_factory else field.default ) value = getattr(obj, name) - if value == default: - continue - elif name == "metadata_only" and not value: + if value == default or name == "metadata_only" and not value: continue + if isinstance(value, simple_types.Color): + value = value.as_int32() name = _plural_to_singular.get(name, name) name = _snake_to_camel.get(name, name) if name in xsd_element.attributes: