[翻译]  Convert string to Enum in Python

[CHINESE]  在Python中将字符串转换为Enum


I wonder what's the correct way of converting (deserializing) a string to a Python's Enum class. Seems like getattr(YourEnumType, str) does the job, but I'm not sure if it's safe enough.

我想知道将字符串转换(反序列化)到Python的Enum类的正确方法是什么。看起来像getattr(YourEnumType,str)完成这项工作,但我不确定它是否足够安全。

Just to be more specific, I would like to convert a 'debug'string to an Enum object like this:

更具体地说,我想将'debug'string转换为Enum对象,如下所示:

class BuildType(Enum):
    debug = 200
    release = 400

3 个解决方案

#1


63  

This functionality is already built in to Enum [1]:

此功能已内置于Enum [1]中:

>>> from enum import Enum
>>> class Build(Enum):
...   debug = 200
...   build = 400
... 
>>> Build['debug']
<Build.debug: 200>

[1] Official docs: Enum programmatic access

[1]官方文档:Enum程序访问

#2


4  

Another alternative (especially useful if your strings don't map 1-1 to your enum cases) is to add a staticmethod to your Enum, e.g.:

另一个替代方案(如果你的字符串没有将1-1映射到枚举的情况下特别有用)是为你的枚举添加一个静态方法,例如:

class QuestionType(enum.Enum):
    MULTI_SELECT = "multi"
    SINGLE_SELECT = "single"

    @staticmethod
    def from_str(label):
        if label in ('single', 'singleSelect'):
            return QuestionType.SINGLE_SELECT
        elif label in ('multi', 'multiSelect'):
            return QuestionType.MULTI_SELECT
        else:
            raise NotImplementedError

Then you can do question_type = QuestionType.from_str('singleSelect')

然后你可以做question_type = QuestionType.from_str('singleSelect')

#3


1  

def custom_enum(typename, items_dict):
    class_definition = """
from enum import Enum

class {}(Enum):
    {}""".format(typename, '\n    '.join(['{} = {}'.format(k, v) for k, v in items_dict.items()]))

    namespace = dict(__name__='enum_%s' % typename)
    exec(class_definition, namespace)
    result = namespace[typename]
    result._source = class_definition
    return result

MyEnum = custom_enum('MyEnum', {'a': 123, 'b': 321})
print(MyEnum.a, MyEnum.b)

Or you need to convert string to known Enum?

或者你需要将字符串转换为已知的枚举?

class MyEnum(Enum):
    a = 'aaa'
    b = 123

print(MyEnum('aaa'), MyEnum(123))

Or:

要么:

class BuildType(Enum):
    debug = 200
    release = 400

print(BuildType.__dict__['debug'])

print(eval('BuildType.debug'))
print(type(eval('BuildType.debug')))    
print(eval(BuildType.__name__ + '.debug'))  # for work with code refactoring

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号