5

I like Enum a lot and I would like to do the following:

class Color(Enum):
    green = 0
    red = 1
    blue = 1

for color in Color:
    print(color.name)
    print(color.value)

As you can see, there are duplicate values in Color class. What class alternative can I use in this case that supports iterable, name, value?

user1502776
  • 553
  • 7
  • 17
  • Take a look at: http://stackoverflow.com/a/1695250/5399734 and other nice answers under that question. – nalzok Aug 01 '16 at 04:04

1 Answers1

7

Are you asking how you can have Color.red and Color.blue without blue being an alias for red?

If yes, you'll want to use the aenum1 library and it would look something like:

from aenum import Enum, NoAlias

# python 3
class Color(Enum, settings=NoAlias):
    green = 0
    red = 1
    blue = 1

# python 2
class Color(Enum):
    _order_ = 'green red blue'
    _settings_ = NoAlias
    green = 0
    red = 1
    blue = 1

And in use:

for color in Color:
    print(color.name)
    print(color.value)

# green
# 0
# red
# 1
# blue
# 1

The downside of using NoAlias is by-value lookups are disabled (you can't do Color(1)).


1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • Awesome !, I was using Enum the built in "enum", but didn't know there exists Enum from "aenum" with NoAlias setting. Thank you! – user1502776 Aug 01 '16 at 05:55
  • 1
    @user1502776: If you don't need the other `Enum` goodies (iterating through the class, length of the class, etc.) then you may want to use the `NamedConstant` class from `aenum`. – Ethan Furman Aug 01 '16 at 16:24