相关疑难解决方法(0)

Python 中基于字符串的枚举

要封装我使用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!)
Run Code Online (Sandbox Code Playgroud)

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

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

select_query2 = select(...).where(Process.status == MyEnum.state1)  # throws exeption
Run Code Online (Sandbox Code Playgroud)

如何避免调用额外的类型转换(str(state)以上)或底层值(state.value)?

python string enums python-3.x

12
推荐指数
6
解决办法
1万
查看次数

标签 统计

enums ×1

python ×1

python-3.x ×1

string ×1