Python Enums for Humans (gist.github.com)

10 points by wuster ↗ HN
I've been doing Python web apps for a few years. All of them have involved some pattern of declaring runtime vars to represent DB values, and also mapping those DB values to user-facing display values in your view templates. The practice of keeping the { var --> value } and { value --> display string } maps separately led to annoying dev-time bugs. Here's my short and easy solution.

MIT License. Enjoy.

4 comments

[ 2.3 ms ] story [ 18.6 ms ] thread
Does nobody else find the repetition objectionable? e.g. NEW = ('N', 'New'), If your values have good names, you can easily deduce "Some Constant" from SOME_CONSTANT or vice-versa. While I'm at it, having abbreviations built-in seems iffy too.
The apparent repetition is due to the triviality of the example. Imagine if you had to translate the display string or change the display name without renaming all of your code references to the constant.
What makes that better than just using strings?
[ Edit: add more context ]

My use case for this is to map between the database and application logic.

In the example, the short string 'N' is for storage in a db column, *.NEW is for use in code, and "New" is for use to display in an UI. You don't necessarily want to persist the display or var name because you may want to rename them in the app later. IMO it's a bad idea to store display representations as data.