2021年3月17日星期三

Output enum name as enum value in a dict showing class attributes in Python

I have an enum and a dataclass as following.

class Mode(Enum):      MODE_A = auto()      MODE_B = auto()    @dataclass  class BaseDataClass:      a: int      b: int      c: int      mode: Mode        def to_dict(self):          return vars(self)  

the to_dict function displays

b = BaseDataClass(a=1, b=2, c=3, mode=Mode.MODE_A)  b.to_dict()    > {'a': 1, 'b': 2, 'c': 3, 'mode': <Mode.MODE_A: 1>}  

I'd like to output the mode name as its value like 'mode': 'MODE_A'. I tried to use dunder methods like __str__ and __repr__ in the enum class but it didn't work. AS it is supposed not to edit __dict__ values, Does anyone suggest a good way to achieve this?

https://stackoverflow.com/questions/66683305/output-enum-name-as-enum-value-in-a-dict-showing-class-attributes-in-python March 18, 2021 at 08:47AM

没有评论:

发表评论