Hacker News new | past | comments | ask | show | jobs | submit login

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




I'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.)


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


Oh, 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!


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


I see, okay, this all makes sense. Thanks for the concise explanation!




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: