两组常量之间的转换

问题描述 投票:0回答:1

我有两个枚举

NAME
ALIAS
,它们保证具有相同数量的常量,并且我需要一种方法将每个常量从
NAME
转换为对应的
ALIAS
中的常量,反之亦然。例如:

def name_to_alias(name):
    if name == Name.PAUL:
        return Alias.STARCHILD
    elif name == Name.GENE:
        return Alias.DEMON
    ...

def alias_to_name(alias):
    if alias == Alias.STARCHILD:
        return Name.PAUL
    elif alias == Alias.DEMON:
        return Name.GENE
    ...

我不想维护这样的两个函数(或字典)。理想情况下,我将枚举映射放在单个数据结构中,我可以从两个转换函数访问它。

我在想类似的事情:

mappings = {
    Name.PAUL: Alias.STARCHILD
    Name.GENE: Alias.DEMON
    ...
}

这适用于从

Name
转换为
Alias
,但相反的情况可能会出现问题(如果我犯了复制粘贴错误并最终得到两个具有相同值的字典键会发生什么?)。有没有一种简单安全的方法来实现这一目标?

python dictionary
1个回答
0
投票

考虑到映射中可能会出现多个名称可能具有相同别名的安全函数应该引发错误,例如

mappings = {
    Name.PAUL: Alias.STARCHILD,
    Name.GENE: Alias.DEMON,
    Name.PETER: Alias.CATMAN,
    Name.ALICE: Alias.DEMON
}

def alias_to_name(alias):
#check if the alias is more than once in the mappings and raise an error
    if list(mappings.values()).count(alias) > 1:
        raise ValueError('Alias is not unique', alias, [name for name, a in mappings.items() if a == alias])
    else:
        return [name for name, a in mappings.items() if a == alias]

就会输出

('Alias is not unique', <Alias.DEMON: 2>, [<Name.GENE: 2>, <Name.ALICE: 4>])

© www.soinside.com 2019 - 2024. All rights reserved.