sixtstorm1 sixtstorm1 - 12 days ago 6
Python Question

How to define custom properties in enumeration in Python (Javascript-like)

In JavaScript we can do this:

var Color = {
YELLOW: { value: 1, displayString: "Yellow" },
GREEN: { value: 2, displayString: "Green" },
}


So I can call:

Color.YELLOW.displayString


In Java we can do this:

public enum Color {

YELLOW (1, "Yellow"),
GREEN (2, "Green"),

private Color(String value, int displayString){
this.value = value;
this.displayString = displayString;
}

private final int value;
private final String displayString;

public String getValue() {return value;}
public String getDisplayString() {return displayString;}
}


So I can call:

Color.YELLOW.getDisplayString()


After much research I haven't found a clean way to do this in Python using the built-in Enum module. How can I do this?

Thanks

Answer

There are two concepts involved here: enumerations and attribute-style access to object members that can be initialised inline. For the latter, you'll need some kind of custom class, but since you want something very straightforward, a namedtuple is sufficient for that. So, combining namedtuple and enum, this could be a solution:

from enum import Enum
from collections import namedtuple

Color = namedtuple('Color', ['value', 'displayString'])

class Colors(Enum):

    @property
    def displayString(self):
        return self.value.displayString

    yellow = Color(1, 'Yellow')
    green = Color(2, 'Green')

print(Colors.yellow.displayString)
Comments