gpt4 book ai didi

python - 可以在 Enum 中添加自定义错误以显示有效值吗?

转载 作者:行者123 更新时间:2023-12-04 07:13:46 25 4
gpt4 key购买 nike

假设我有

from enum import Enum

class SomeType(Enum):
TYPEA = 'type_a'
TYPEB = 'type_b'
TYPEC = 'type_c'
如果我现在做
SomeType('type_a')
我会得到
<SomeType.TYPEA: 'type_a'>
正如预期的那样。当我做
SomeType('type_o')
我会收到

ValueError: 'type_o' is not a valid SomeType


这也是意料之中的。
我的问题是:可以以某种方式轻松自定义错误以显示所有有效类型吗?所以,就我而言,我想要

ValueError: 'type_o' is not a valid SomeType. Valid types are'type_a', 'type_b', 'type_c'.

最佳答案

使用 _missing_方法:

from enum import Enum

class SomeType(Enum):
TYPEA = 'type_a'
TYPEB = 'type_b'
TYPEC = 'type_c'
@classmethod
def _missing_(cls, value):
raise ValueError(
'%r is not a valid %s. Valid types: %s' % (
value,
cls.__name__,
', '.join([repr(m.value) for m in cls]),
))
并在使用中:
>>> SomeType('type_a')
<SomeType.TYPEA: 'type_a'>

>>> SomeType('type_o')
ValueError: 'type_o' is not a valid SomeType

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
...
ValueError: 'type_o' is not a valid SomeType. Valid types: 'type_a', 'type_b', 'type_c'
如您所见,异常链接有点笨拙,因为 Enum 本身会引发“主要” ValueError ,您丢失的错误在链中。根据您的需要,您可以缩小 ValueError您在 _missing_ 中提出的只包含有效类型:
from enum import Enum

class SomeType(Enum):
TYPEA = 'type_a'
TYPEB = 'type_b'
TYPEC = 'type_c'
@classmethod
def _missing_(cls, value):
raise ValueError(
'Valid types: %s' % (
', '.join([repr(m.value) for m in cls]),
)
并在使用中:
>>> SomeType('type_o')
ValueError: 'type_o' is not a valid SomeType

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
...
ValueError: Valid types: 'type_a', 'type_b', 'type_c'

披露:我是 Python stdlib Enum 的作者, enum34 backport ,以及 Advanced Enumeration ( aenum )图书馆。

关于python - 可以在 Enum 中添加自定义错误以显示有效值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68899057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com