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

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




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

Search: