top | item 41254022

(no title)

binarycoffee | 1 year 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.

discuss

order

Austizzle|1 year ago

Fascinating, how did you get the type hint on the `type` class variable to be correct? (Or is this not visible to mypy?)

bmitc|1 year ago

Does MyPy properly validate the use of these types?

Do you have anything public that elaborates on this?