Python中基于字符串的枚举 [英] String-based enum in Python

查看:40
本文介绍了Python中基于字符串的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要封装状态列表,请使用 enum 模块:

To encapsulate a list of states I am using enum module:

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!)

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

However, the issue is that I need to seamlessly use the values as strings in many contexts in my script, like:

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 )?

How to do it avoiding calling additional type conversion (str(state) above) or the underlying value (state.value)?

推荐答案

似乎与 Enum 同时从 str 类继承就足够了:

It seems that it is enough to inherit from str class at the same time as Enum:

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

棘手的部分是,继承链中类的顺序很重要,如下所示:

The tricky part is that the order of classes in the inheritance chain is important as this:

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

抛出:

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

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

With the correct class the following operations on MyEnum are fine:

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


作为旁注,看来格式化的格式不需要特殊的继承技巧字符串甚至仅对 Enum 继承有效:

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

这篇关于Python中基于字符串的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆