Skip to content

Commit

Permalink
use pydantic Color type (#100)
Browse files Browse the repository at this point in the history
* use pydantic color

* add int method
  • Loading branch information
tlambert03 authored Aug 10, 2021
1 parent 05ddffb commit c5ff727
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
33 changes: 33 additions & 0 deletions src/ome_autogen.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"],
Expand Down Expand Up @@ -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)

Expand Down
7 changes: 4 additions & 3 deletions src/ome_types/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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:
Expand Down

0 comments on commit c5ff727

Please sign in to comment.