枚举 _missing_ 函数不会消除 ValueError

Sam*_*ett 7 python enums python-3.x

我正在尝试设置一个枚举,None如果找不到该值,它将返回。该文档提到了一个 function _missing_,但没有解释有关该函数的任何细节:

\n\n
\n

_missing_\xe2\x80\x93 未找到值时使用的查找函数;可能会被覆盖

\n
\n\n

环顾四周后,这似乎是classmethod带有签名的cls, value,所以我尝试设置它,但它不起作用。

\n\n
>>> class G(enum.Enum):\n...   @classmethod\n...   def _missing_(cls, value):\n...     return None\n...   a = 1\n...\n>>> G(1)\n<G.a: 1>\n>>> G(2)\nTraceback (most recent call last):\n  ...\nValueError: 2 is not a valid G\n>>> G[\'b\']\nKeyError: \'b\'\n>>> G.b\nAttributeError: b\n
Run Code Online (Sandbox Code Playgroud)\n\n

谷歌搜索表明_missing_仅捕获调用情况中的 ValueError ,因此 KeyError 和 TypeError 并不让我感到惊讶,但我不知道为什么G(2)会引发 ValueError 而不是返回None

\n

Sam*_*ett 7

关于该函数,文档缺少的两个主要内容_missing_是问题中的签名,以及返回类型必须是枚举的成员这一事实。如果None返回,则错误不会被消除。

此行为只能通过源代码检查或不同的错误消息看到:

>>> class G(enum.Enum):
...   @classmethod
...   def _missing_(cls, value):
...     return "a truthy value"  # I suspected that the error may have been caused by a falsey return
...   a = 1
...
>>> G(2)
ValueError: 2 is not a valid G
During handling of the above exception, another exception occured:
Traceback (most recent call last):
  ...
TypeError: error in G._missing_: returned 'a truthy value' instead of None or a valid member
Run Code Online (Sandbox Code Playgroud)

因此,处理这种情况的唯一方法是使用 Sentinal G.noneG.nullG.missing任何最合适的值。

  • 哇,好尴尬啊!我将在接下来的几天内尝试为此提供补丁。随意打败我吧!:-) (2认同)