Enum auto And unique Guard Duplicate Values

Build enums with auto numbering and guard duplicate values with the unique decorator, then look members up by name, value, or identity.

PythonData Integrity

Code

pythonsnippet
34 lines
from enum import Enum, auto, unique


@unique
class Planet(Enum):
    MERCURY = auto()
    VENUS = auto()
    EARTH = auto()
    MARS = auto()


def main() -> None:
    print('members:', [p.name for p in Planet])
    print('auto values:', [p.value for p in Planet])

    # 名字查找与值查找
    print('by name:', Planet['EARTH'].value)
    print('by value:', Planet(3).name)

    # 成员是单例,可用身份比较
    print('singleton:', Planet.MARS is Planet['MARS'])

    # auto 值按定义顺序递增;重复值会被 @unique 拦截
    try:
        @unique
        class Bad(Enum):
            A = 1
            B = 1
    except ValueError as exc:
        print('unique rejected:', str(exc).split(':')[0])


if __name__ == '__main__':
    main()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

members: ['MERCURY', 'VENUS', 'EARTH', 'MARS']
auto values: [1, 2, 3, 4]
by name: 3
by value: EARTH
singleton: True
unique rejected: duplicate values found in <enum 'Bad'>

How the snippet works

Count the classes Planet and Bad and the function main as the entire surface area of Enum auto And unique Guard Duplicate Values.

Applying it

The run emits 6 labeled sections — members:, auto values:, by name:, by value:, singleton:, unique rejected: — one per step.

Statements that matter

except ValueError as exc:
    print('unique rejected:', str(exc).split(':')[0])

Interactive Tools for This Topic

FAQ

What does Enum auto And unique Guard Duplicate Values print when run?
Invoke the file as-is — the `members:`, `auto values:`, `by name:` prefixes identify which step printed each line.