diff options
author | Ethan Furman <ethan@stoneleaf.us> | 2013-07-19 00:05:39 (GMT) |
---|---|---|
committer | Ethan Furman <ethan@stoneleaf.us> | 2013-07-19 00:05:39 (GMT) |
commit | f24bb35a69d18a05047399eadc63b4be092aee71 (patch) | |
tree | d2cb70aa9a38166dc38bf54a056f238f43caf747 /Lib/enum.py | |
parent | d85032e25d4f9864ecc694a02a6678b4e6069739 (diff) | |
download | cpython-f24bb35a69d18a05047399eadc63b4be092aee71.zip cpython-f24bb35a69d18a05047399eadc63b4be092aee71.tar.gz cpython-f24bb35a69d18a05047399eadc63b4be092aee71.tar.bz2 |
closes issue18042 -- a `unique` decorator is added to enum.py
The docs also clarify the 'Interesting Example' duplicate-free enum is for
demonstration purposes.
Diffstat (limited to 'Lib/enum.py')
-rw-r--r-- | Lib/enum.py | 16 |
1 files changed, 15 insertions, 1 deletions
diff --git a/Lib/enum.py b/Lib/enum.py index 775489b..38d95c5 100644 --- a/Lib/enum.py +++ b/Lib/enum.py @@ -4,7 +4,7 @@ import sys from collections import OrderedDict from types import MappingProxyType -__all__ = ['Enum', 'IntEnum'] +__all__ = ['Enum', 'IntEnum', 'unique'] class _RouteClassAttributeToGetattr: @@ -463,3 +463,17 @@ class Enum(metaclass=EnumMeta): class IntEnum(int, Enum): """Enum where members are also (and must be) ints""" + + +def unique(enumeration): + """Class decorator for enumerations ensuring unique member values.""" + duplicates = [] + for name, member in enumeration.__members__.items(): + if name != member.name: + duplicates.append((name, member.name)) + if duplicates: + alias_details = ', '.join( + ["%s -> %s" % (alias, name) for (alias, name) in duplicates]) + raise ValueError('duplicate values found in %r: %s' % + (enumeration, alias_details)) + return enumeration |