【发布时间】:2021-10-14 15:33:27
【问题描述】:
我正在尝试在枚举失败时重新定义它,但随后会引发错误。
我的代码如下所示:
from enum import Enum
class FooEnum(Enum):
try:
foo = 3/0
except Exception as my_exception_instance:
print('An error occurred:', my_exception_instance)
foo=0
目标是3/0 会引发异常,然后重新定义foo。
但是,当我按原样运行它时,会显示打印消息,但会引发另一个错误,这对我来说没有意义。这是输出和堆栈跟踪:
An error occurred: division by zero
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-489d2391f28b> in <module>
1 from enum import Enum
2
----> 3 class FooEnum(Enum):
4 try:
5 foo = 3/0
<ipython-input-10-489d2391f28b> in FooEnum()
6 except Exception as my_exception_instance:
7 print('An error occurred:', my_exception_instance)
----> 8 foo=0
/usr/lib/python3.6/enum.py in __setitem__(self, key, value)
90 elif key in self._member_names:
91 # descriptor overwriting an enum?
---> 92 raise TypeError('Attempted to reuse key: %r' % key)
93 elif not _is_descriptor(value):
94 if key in self:
TypeError: Attempted to reuse key: 'my_exception_instance'
摆脱此错误的唯一方法是在捕获异常时删除它的使用:
from enum import Enum
class FooEnum(Enum):
try:
foo = 3/0
except:
print('An error occurred')
foo=0
然后它只是输出:An error occurred
我正在使用 python 3.6.9
编辑 以下代码更接近我的用例:
import tensorflow as tf
from enum import Enum
class VisualModels(Enum):
try:
MobileNet = tf.keras.applications.MobileNetV2
except Exception as e:
print(f'MobileNetV2 Not found, using MobileNet instead. Error: {e}.')
MobileNet = tf.keras.applications.MobileNet
# more models are defined similarly
【问题讨论】:
标签: python exception enums python-3.6