pythonenums

Parameterized Enums in Python


In Python, I want to have an enum-like data structure that can be used like the Option enum in Rust: the enum has parameterized member, and an unparameterized, e.g.,

enum MyType<T> {
    A,
    B(T),
}

would allow me to use MyType.A, MyType.B(1) and MyType.B(2).

What is the most elegant way to achieve this behavior in Python? So far, my only solution would involve subclasses A, B of an abstract class MyType. But the drawback is that this requires me to do instance checking instead of simply using is.

My specific use case is the following: My data can be either replicated across multiple processes or sharded. If it's sharded, I need the number of shards. My function will process data depending on whether it's replicated or sharded.

If enums aren't useful for this, how to better implement this?


Solution

  • As Sayandip Dutta mentioned this article in the comments, where the author Kobzol proposes to use Unions to represent an enumeration of different kinds of objects that represent different instantiations of something (in his case, network packets). This is, in fact, very similar to my problem. So, I ended up representing my data as follows:

    @dataclass
    class A:
        pass
    
    
    @dataclass
    class B:
        t: T
    
    
    MyType = Union[A, B]
    

    The disadvantage of this approach is that I have to use isinstance to distinguish between the different instantiations instead of is, which is usually quite costly.