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.displ
Solution 1:
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'])
classColors(Enum):
@propertydefdisplayString(self):
return self.value.displayString
yellow = Color(1, 'Yellow')
green = Color(2, 'Green')
print(Colors.yellow.displayString)
Solution 2:
Here is another approach, that is the code from: https://github.com/hzdg/django-enumfields
import enum
import inspect
classColorEnumMeta(enum.EnumMeta):
def__new__(mcs, name, bases, attrs):
DisplayStrings = attrs.get('DisplayStrings')
if DisplayStrings isnotNoneand inspect.isclass(DisplayStrings):
del attrs['DisplayStrings']
ifhasattr(attrs, '_member_names'):
attrs._member_names.remove('DisplayStrings')
obj = super().__new__(mcs, name, bases, attrs)
for m in obj:
m.display_string = getattr(DisplayStrings, m.name, None)
return obj
classColor(enum.Enum, metaclass=ColorEnumMeta):
yellow = 1
green = 2classDisplayStrings:
yellow = 'Yellow'
green = 'Green'print(Color.yellow.display_string) # 'Yellow'
or something that is based on this code, but a bit shorter:
import enum
classColorEnumMeta(enum.EnumMeta):
def__new__(mcs, name, bases, attrs):
obj = super().__new__(mcs, name, bases, attrs)
obj._value2member_map_ = {}
for m in obj:
value, display_string = m.value
m._value_ = value
m.display_string = display_string
obj._value2member_map_[value] = m
return obj
classColor(enum.Enum, metaclass=ColorEnumMeta):
yellow = 1, 'Yellow'
green = 2, 'Green'print(Color.yellow.display_string) # 'Yellow'
Solution 3:
You can use a dictionary in python:
Color = {
'YELLOW': { 'value': 1, 'displayString': "Yellow" },
'GREEN': { 'value': 2, 'displayString': "Green" }
}
Color['YELLOW']['displayString']
Solution 4:
You should normally never include literals like this in your code. The content should come from a file or database. But you can see how to build it up
>>> from collections import namedtuple
>>> Color = namedtuple("color", "YELLOW,GREEN")(
namedtuple("yellow", "value,display_string")(1, "yellow"),
namedtuple("green", "value,display_string")(2, "green"))
>>> Color.YELLOW.display_string
'yellow'
This also works for older Pythons that don't support enum
Post a Comment for "How To Define Custom Properties In Enumeration In Python (javascript-like)"