hzdg / django-modeltools

Enums in your models, template strings for FileField names…

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use PEP435 Enums

matthewwithanm opened this issue · comments

Now that enums are going to be added to the stdlib (and a few backports have emerged), we should probably update modeltools to use them. Maybe we could extend them and add some convenience methods (like choices()).

This would be a breaking change.

I think this might not work out. The hurdles are that we need our enums to specify two additional pieces of information: order (for the "choices" list) and labels.

Order isn't a problem in Python 3, but in 2.X, you need an extra __order__ attribute:

class Color(Enum):
    __order__ = 'RED GREEN BLUE'

    RED = 'r'
    GREEN = 'g'
    BLUE = 'b'

There doesn't seem a really elegant way to do labels; the best I can come up with is a nested class, which isn't very DRY:

class Color(Enum):
    __order__ = 'RED GREEN BLUE'

    RED = 'r'
    GREEN = 'g'
    BLUE = 'b'

    class Labels:
        RED = 'The red label'

This can be a fallback for when you need something that can't be derived from the enum name, but it's still kind of gross. We could use (value, label) for the attributes but I feel like that obscures things.

It might just be best to stick with the current syntax:

Color = Enum(
    ('RED', 'r', 'Red'),
    ('GREEN', 'g', 'Green'),
    ('BLUE', 'b', 'Blue'),
)

/cc @kenzic @ryanbagwell @kkubasik @simul14 @cwood @lettertwo