I am trying to write a simple function that takes a string and an enum type and tries to create the matching enum instance and give a nice error message if not.
However, i just tried out the new rust type checkers and noticed that zuban gives the following error
error: Enum() expects a string literal as the first argument [misc]
I actually had that (although zuban then complained about that when i tried passing in the enum type…) but unfortunatley it doesnt work regardless because i need to iterate over the enum to get the options for my error message ;(
I think what you want here is to constrain the type of key to the enum values defined in enum_type. For that I think you’d need the proposed PEP 827 (Type Manipulation) which would allow something like
Though I don’t know how to type the .lower() part. But maybe that’s okay – if the caller gets the case wrong they’ll get a type error.
EDIT:* I chatted with Claude about this and Attrs does not produce a union. You could try KeyOf but it would require annotating the enum, which is uncommon. So, no, unless we add new rules for Enum subclasses. Also, I should have used [E: Enum].
This is probably just a small problem with Enums that hasn’t come up before. Enums are quite special and structural typing might be a bit off in some ways. @JanEricNitschke just open issues on GitHub and I hope to eventually have time to look at it.