6

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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.