Files
kittycad.py/generate/union-type.py.jinja2

50 lines
1.6 KiB
Plaintext
Raw Normal View History

from typing import Dict, Any, Union, Type, TypeVar
from typing_extensions import Self
import attr
GY = TypeVar("GY", bound="{{name}}")
@attr.s(auto_attribs=True)
class {{name}}:
{% if description %}
"""{{description}}"""
{% endif %}
type: Union[
{% for type in types %}
{{type.name}},
{% endfor %}
]
def __init__(self,
type: Union[
{% for type in types %}
{{type.name}},
{% endfor %}
]):
self.type = type
def to_dict(self) -> Dict[str, Any]:
{% for type in types %}{% if loop.first %}
if isinstance(self.type, {{type.name}}):
{{type.var0}} : {{type.name}} = self.type
return {{type.var0}}.to_dict()
{% else %}elif isinstance(self.type, {{type.name}}):
{{type.var0}} : {{type.name}} = self.type
return {{type.var0}}.to_dict()
{% endif %}{% endfor %}
raise Exception("Unknown type")
@classmethod
def from_dict(cls: Type[GY], d: Dict[str, Any]) -> GY:
{% for type in types %}{% if loop.first %}
if d.get("type") == "{{type.name}}":
{{type.var1}} : {{type.name}} = {{type.name}}()
{{type.var1}}.from_dict(d)
return cls(type={{type.var1}})
{% else %}elif d.get("type") == "{{type.name}}":
{{type.var1}} : {{type.name}} = {{type.name}}()
{{type.var1}}.from_dict(d)
return cls(type={{type.var1}})
{% endif %}{% endfor %}
raise Exception("Unknown type")