我試圖在列舉失敗時重新定義它,但隨后引發了錯誤。
我的代碼如下所示:
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
uj5u.com熱心網友回復:
發生這種情況的原因是:
_EnumDict跟蹤所有使用過的名字_EnumDict認為my_exception_instance應該是會員- Python
as在離開except子句 時清除變數- 通過分配
None給my_exception_instance(然后洗掉變數) - 導致
_EnumDict認為密鑰被重用
- 通過分配
一種解決方法(從 Python 3.7 開始)是添加my_exception_instance到_ignore_1屬性:
class FooEnum(Enum):
_ignore_ = 'my_exception_instance'
try:
foo = 3/0
except Exception as my_exception_instance:
print('An error occurred:', my_exception_instance)
foo=0
另一個解決方法是 makemy_exception_instance是一個全域的:
class FooEnum(Enum):
global my_exception_instance
try:
foo = 3/0
except Exception as my_exception_instance:
print('An error occurred:', my_exception_instance)
foo=0
最后,如果您不想在列舉的主體中使用 try/except:
class FallbackEnum(Enum):
def __new__(cls, *values):
# first actual value wins
member = object.__new__(cls)
fallback = False
for v in values:
try:
member._value_ = eval(v)
break
except Exception as e:
print('%s error: %s' % (v, e))
fallback = True
continue
else:
# never found a value
raise ValueError('no valid value found')
# if we get here, we found a value
if fallback:
# if the first value didn't work, print the one we did use
print(' using %s' % v)
return member
并在使用中:
>>> class FooEnum(FallbackEnum):
... foo = '3/0', '0'
...
3/0 error: division by zero
using 0
>>> list(FooEnum)
[<FooEnum.foo: 0>]
1aenum如果停留在 Python 3.6,您可以使用。
Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/328258.html
標籤:Python 例外 枚举 python-3.6
上一篇:Netbeans:意外例外
