As much as I like Rust for its ergonomic features, university has forced me to use Python for the past couple of months, especially because of the hype for machine learning and data science.
One of the biggest things that I missed from the rust experience was enumerable data types whose variants can wrap around different datatypes.
Although Python has the answer to creating structs as dataclasses, including support for structural match expressions in recent versions, most tutorials will suggest Union types as the equivalent to Rust’s enums.
I highly encourage you to try out the code snippets and follow along with this article. Use the collapse explanation button to copy multiple code blocks in one go.
Naive draft
This allows us to define functions that ingest the Glass datatype.
For example
Will output
Ah a Dr. Pepper, what a fine taste!Pitfalls
No direct variant access
What if we had another Union with same variant names in the same file?
Now we try to instantiate a Glass Full of lemonade.
Python will error out since Full now refers to the new variant of the union type Inventory.
Traceback (most recent call last): File "<python-input-11>", line 1, in <module> lemonade = Full("lemonade") TypeError: Full.__init__() missing 1 required positional argument: 'gems'We can’t instantiate variants as members of the Glass namespace. The following code does not work.
This can be partially solved by keeping just the Glass type inside a module. Here we have saved the file as glass_enum.py. From a different module we can access the variants as glass_enum.Empty and glass_enum.Full.
Now any function outside the module has to ingest a rather confusing argument of type glass_enum.Glass.
Since module namespacing only causes more confusion, we will discard this idea.
No methods on the enum itself
Python also disallows methods from being defined on Union types. In the case of our concrete example, we can’t add methods to the Glass type.
The following code uses a hypothetical is_empty() method on the Glass union type which is not allowed. Hence the code won’t run.
To define a method like is_empty(), it must be implemented on both the classes Full and Empty. This gets tedious for 3 or more variants.
Python is a sneaky language
Last week I discovered that Python allows creating nested classes to keep things organized.
Python will happily run the above code and we can access the “variants” under the Glass namespace.
If only we could register the variants as the Glass type itself and inherit all its methods.
Redecorate
We can define a decorator that takes all of the nested dataclasses and makes them inherit the outer class.
The inheritance means all methods of the outer class are available on the nested classes and any object of a nested class isinstance of the outer class.
That’s all there is to the magic! Now we can simply add this decorator above the previous class declaration and the variants like Glass.Empty and Glass.Full would be of the type Glass.
As a bonus, the variants will also inherit any methods defined on the Glass type.
Note how the report_drink method accepts a self of type Glass and the match arms compare it with Glass.Empty and Glass.Full.
These methods get automatically called via the method resolution order chain due to the inheritance.
The following code runs just fine.
Closing thoughts
Those 6 lines are the bare minimum to get well organized and namespaced algebraic enums in Python that are somewhat comparable to the ones in Rust. These enums also play nicely with static type checkers, goto-definitions will lead you to the correct class definition.
I have packaged this decorator with a couple more typing restrictions into a library at github:lavafroth/ape.
I hope you enjoyed this foray into contorting Python.
.png)


