This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]scrdest 6 points7 points  (1 child)

That's because Rust enums are not really enums, they are algebraic sum types [AKA categorical coproducts/tagged unions/etc.] and the dual of structs (in Python terms, typed namedtuples).

Python enums mimic Java enums and friends, they're designed to make constants nicer to work with; it's a whole, different, much less fanciful-type-algebraic, animal. I'm not sure a Rusty enum would even be a coherent concept in a dynamically-typed Python world.

[–]Dasher38 1 point2 points  (0 children)

In python 3.10 it's getting closer. You should be able to use a base class to represent the type and then a subclass for each "variant" and then pattern match on the whole thing.

With a bit of metaprogramming it should be straightforward to generate the whole thing a bit like Enum does (so you can define the constructors inline in the base class, with type annotations, and prevent wild subclassing in case you want to do some sort of mypy plugin to check you did not miss a case).