Python中基于字符串的枚举

ph

封装状态列表我正在使用enum模块:

from enum import Enum

class MyEnum(Enum):
    state1='state1'
    state2 = 'state2'

state = MyEnum.state1
MyEnum['state1'] == state  # here it works
'state1' == state  # here it does not throw but returns False (fail!)

但是,问题是我需要在脚本的许多上下文中将这些值无缝地用作字符串,例如:

select_query1 = select(...).where(Process.status == str(MyEnum.state1))  # works but ugly

select_query2 = select(...).where(Process.status == MyEnum.state1)  # throws exeption

如何避免调用额外的类型转换(str(state)上面)或基础值(state.value)?

ph

似乎可以同时从str继承Enum

class MyEnum(str, Enum):
    state1='state1'
    state2 = 'state2'

棘手的是,继承链中类的顺序很重要,因为:

class MyEnum(Enum, str):
    state1='state1'
    state2 = 'state2'

抛出:

TypeError: new enumerations should be created as `EnumName([mixin_type, ...] [data_type,] enum_type)`

使用正确的类,可以进行以下操作MyEnum

print('This is the state value: ' + state)

作为附带说明,似乎格式化的字符串不需要特殊的继承技巧,即使格式化Enum适用于继承:

msg = f'This is the state value: {state}'  # works without inheriting from str

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章