Skip to content

Commit

Permalink
Improve typing hints in generated code (#7)
Browse files Browse the repository at this point in the history
This fixes the following runtime errors:
* Correctly set default to "None" for TiffData/UUID

and these typing errors:
* Cast default values for constrained integer attributes (both mypy and
  pywright were complaining about this)
* Drop use of conlist in ROI/Union in favor of Field (only mypy noticed this)
  • Loading branch information
jmuhlich authored Jul 14, 2020
1 parent 749d46d commit 0c0c2fd
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/ome_autogen.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@
"XMLAnnotation": ("Optional[str]", "None", "from typing import Optional\n\n",),
"BinData/Length": ("int", None, None),
"ROI/Union": (
"conlist(Shape, min_items=1)",
"List[Shape] = Field(..., min_items=1)",
None,
"from pydantic.types import conlist\nfrom .shape import Shape",
"from pydantic import Field\nfrom .shape import Shape",
),
"TiffData/UUID": (
r'Optional[dataclass(type("UUID", (), {"__annotations__": '
r'{"file_name": str, "value": UniversallyUniqueIdentifier}}))]',
None,
"None",
"from typing import Optional\n\nfrom "
".simple_types import UniversallyUniqueIdentifier",
),
Expand Down Expand Up @@ -205,6 +205,12 @@ def is_enum_type(self) -> bool:
def is_builtin_type(self) -> bool:
return hasattr(self.type, "python_type")

@property
def is_decimal(self) -> bool:
return self.component.type.is_derived(
self.component.schema.builtin_types()['decimal']
)

@property
def key(self):
p = self.component.parent
Expand Down Expand Up @@ -247,6 +253,8 @@ def imports(self) -> Set[str]:
imports.add("from dataclasses import field")
elif self.is_optional:
imports.add("from typing import Optional")
if self.is_decimal:
imports.add("from typing import cast")
if self.type.is_datetime():
imports.add("from datetime import datetime")
if not self.is_builtin_type and self.type.is_global():
Expand Down Expand Up @@ -324,6 +332,8 @@ def default_val_str(self) -> str:
default_val = f"{self.type_string}('{default_val}')"
elif hasattr(builtins, self.type_string):
default_val = repr(getattr(builtins, self.type_string)(default_val))
if self.is_decimal:
default_val = f"cast({self.type_string}, {default_val})"
else:
default_val = "None"
return f" = {default_val}"
Expand Down

0 comments on commit 0c0c2fd

Please sign in to comment.