What's a case where I'll have a problem if I don't use this decorator? (I've used the Enum class a bit since it became available, but not in any particularly interesting implementations so maybe that's why I've never heard of this.)
What's a case where I'll have a problem if I don't use this decorator? (I've used the Enum class a bit since it became available, but not in any particularly interesting implementations so maybe that's why I've never heard of this.)
In [21]: @enum.unique
...: class Animal(enum.Enum):
...: DOG = 1
...: CAT = 2
...: PIG = 2
...:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-21-cbc1625bb41c> in <module>
1 @enum.unique
----> 2 class Animal(enum.Enum):
3 DOG = 1
4 CAT = 2
5 PIG = 2
~/.virtualenvs/py3/lib/python3.6/enum.py in unique(enumeration)
834 ["%s -> %s" % (alias, name) for (alias, name) in duplicates])
835 raise ValueError('duplicate values found in %r: %s' %
--> 836 (enumeration, alias_details))
837 return enumeration
838
ValueError: duplicate values found in <enum 'Animal'>: PIG -> CAT
It's intended to catch programmer errors - not really useful for small enums like this one, but in a large enum, having duplicates could be difficult to notice, and might cause some insidious bugs.So this is mitigated by using `enum.auto` for setting the values. But I can definitely see how `enum.unique` would be useful if your enums had more specific values.
Thanks for the explanation!
If you are explicitly setting enum values, it causes accidental aliases (duplicate values) to be an error early rather than a source of (potentially subtle) problems later.
It also specifically communicates intent to other readers of the code, which can be just as important if your code has a lot of enums,some of which do use aliasing intentionally.