Hacker News new | ask | show | jobs
by binarycoffee 672 days ago
I needed to reflect Rust enums and went a bit further with that approach. All variants are wrapped in a decorated class, where the decorator automatically computes the union type and adds de/serialization hooks for `cattrs`.

    @enumclass
    class MyEnum:
        class UnitLikeVariant(Variant0Arg): ...
    
        class TupleLikeVariant(Variant2Arg[int, str]): ...
    
        @dataclass
        class StructLikeVariant:
            foo: float
            bar: int

        # The following class variable is automatically generated:
        #
        # type = UnitLikeVariant | TupleLikeVariant | StructLikeVariant
where the `VariantXArg` classes are predefined.
2 comments

Fascinating, how did you get the type hint on the `type` class variable to be correct? (Or is this not visible to mypy?)
Does MyPy properly validate the use of these types?

Do you have anything public that elaborates on this?