You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Enum遍历未输出全部成员,请求排查脚本问题

枚举类遍历丢失成员问题排查

我定义了一个名为SecData的Enum类,用来验证db1与db2之间的键映射关系,但使用for循环遍历该Enum时,未能打印出所有已定义的枚举成员。以下是我的代码及输出结果:

代码示例

from enum import Enum

class SecData(Enum):
    secId = "sectoId"
    anteName = "anteName"
    rAzimuth = "rAzimuth"
    agl = "AboveGroundLevel"
    actualAzimuth = "AntennaHeight"
    actualLatitude = "SectorLat"
    technology = "technology"
    antennaType = "sectorAntennaType"
    actualElectricalTilt = "sectorElecTilt"
    actualMechanicalTilt = "sectorMechTilt"
    sectorNumber = "sectorNum"
    rtsTilt = "rtsTilt"
    band = "sectorBand"
    actualLongitude = "SectorLong"
    actualAntennaheight = "sectorAntennaHeight"
    siteReferenceId = "null"
    retiid4 = "null"
    retiid2 = "null"
    retiid3 = "null"
    NominalId = "null"
    retiid1 = "null"
    status = "null"

for sector in SecData:
    print(sector.name, "-", sector.value)

输出结果

secId - sectoId
anteName - anteName
rAzimuth - rAzimuth
agl - AboveGroundLevel
actualAzimuth - AntennaHeight
actualLatitude - SectorLat
technology - technology
antennaType - sectorAntennaType
actualElectricalTilt - sectorElecTilt
actualMechanicalTilt - sectorMechTilt
sectorNumber - sectorNum
rtsTilt - rtsTilt
band - sectorBand
actualLongitude - SectorLong
actualAntennaheight - sectorAntennaHeight
siteReferenceId - null

问题原因

Python标准库的Enum存在值唯一性约束:所有枚举成员的value必须唯一。你的代码中,siteReferenceId之后的retiid4、retiid2、retiid3、NominalId、retiid1、status这些成员的value均为"null",与siteReferenceId的value重复。此时Enum会将后续成员视为前面成员的别名,遍历枚举类时只会输出第一个出现的成员,别名不会被单独列出。

解决方案

1. 启用重复值检测(快速排查)

使用enum.unique装饰器,当枚举类中出现重复value时会直接抛出ValueError,帮助提前发现问题:

from enum import Enum, unique

@unique
class SecData(Enum):
    # 成员定义保持不变
    ...

运行后会触发报错:ValueError: duplicate values found in <enum 'SecData'>: retiid4 -> siteReferenceId, retiid2 -> siteReferenceId, ...

2. 修改重复的value

如果这些成员需要作为独立项存在,给每个重复的"null"设置唯一值,比如添加后缀区分:

class SecData(Enum):
    # ... 其他成员不变
    siteReferenceId = "null_site"
    retiid4 = "null_retiid4"
    retiid2 = "null_retiid2"
    retiid3 = "null_retiid3"
    NominalId = "null_nominal"
    retiid1 = "null_retiid1"
    status = "null_status"

3. 使用支持重复值的枚举实现

如果业务上确实需要相同value的独立成员,可以使用第三方库aenum(需先安装:pip install aenum),它支持非唯一值的枚举:

from aenum import Enum, NoAlias

class SecData(Enum, settings=NoAlias):
    # 成员定义保持不变
    ...

此时遍历会输出所有成员,即使value重复。


内容的提问来源于stack exchange,提问作者Alok Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 09:25:58