On 2022-05-08, at 13:04, David Hagen <david@drhagen.com> wrote:
Rust-style enums containing both classes and values would be my ideal scenario. I'm very happy to share actual examples from work where I've wished I had robust ADTs if that would help.
I am sympathetic to Rust-style enums (subclasses listed inside the body of the base class). The problem is getting this to work with inheritance in Python. Rust doesn't have inheritance, so it doesn't care. Scala and Swift have a compiler that handles it.
The obvious design (the rejected one in the PEP) would use the `class` keyword within the base class body. The problem is that the base class does not exist at this point (at least not under its name), so something like this will not work:
``` from enum import Enum
class Result(Enum): class Success(Result): ...
class Failure(Result): .... ```
We could have `Enum` do some magic (on top of what it does right now) that it injects itself into the `__bases__` of any class object found among its attributes. Or `Enum` could rebuild each class object found with itself added to the list of bases. This may be worth exploring more, because there are a number of edge cases that I don't know how to deal with from an implementation perspective. _______________________________________________ Typing-sig mailing list -- typing-sig@python.org To unsubscribe send an email to typing-sig-leave@python.org https://mail.python.org/mailman3/lists/typing-sig.python.org/ Member address: jakub@stasiak.at
Hey all, this reminds me that I actually played with the idea of Rust-like enums in Python a while ago and this is what I came up with: https://gist.github.com/jstasiak/7f1687100ec7b2000b5206a537b1a0b0 I focused on what kind of API I wanted and the support for all types of members that Rust has: singletons, "tuple structs" and regular structs. An excerpt: @enum class WebEvent: PageLoad: None KeyPress: tuple[str] class Click: x: int y: int def inspect(event: WebEvent) -> None: match event: case WebEvent.PageLoad: print("Page loaded") case WebEvent.KeyPress(c): print(f"Pressed key {c}") case WebEvent.Click(x=x, y=y): print(f"Clicked on {x}/{y}") Best, Jakub