4 ms·
A funky thing about the Enum class is you may also want the `@enum.unique` decorator in most cases, which enforces the enum/value pair being unique. I found the
by nerdwaller 7y ago
A funky thing about the Enum class is you may also want the `@enum.unique` decorator in most cases, which enforces the enum/value pair being unique. I found the documentation a little misleading until I found that [0].
[0] https://docs.python.org/3/library/enum.html#enum.unique https://docs.python.org/3/library/enum.html#enum.unique
- DonaldPShimoda 7y agoI'm not sure I follow the purpose of this, and the documentation is not terribly elucidating haha. 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.)
- clawlor 7y ago``@enum.unique`` will raise a ValueError if you accidentally include the same value twice in an enum definition: 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.
- DonaldPShimoda 7y agoOh, I get it! This makes sense. 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!
- dragonwriter 7y ago> What's a case where I'll have a problem if I don't use this decorator? 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.
- DonaldPShimoda 7y agoI see, okay, this all makes sense. Thanks for the concise explanation!