![]() |
Having trouble writing an Enum with a custom __new__ method - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Having trouble writing an Enum with a custom __new__ method (/thread-36369.html) |
Having trouble writing an Enum with a custom __new__ method - stevendaprano - Feb-12-2022 I have an enum subclass where I need to associate two pieces of data with each enum. The first is used for the enum value itself, the second needs to be stored as an attribute. Here is an example showing what I am trying to do: from enum import Enum class MyEnum(Enum): MEMBER = ("This is my enum", 1.5) def __new__(cls, value, extra): obj = super().__new__(cls, value) obj._value_ = value obj.extra = extra return objWhat I expect to get is this: MyEnum.MEMBER.value == "This is my enum" # This should return True MyEnum.MEMBER.extra == 1.5 # This should return TrueBut instead, I get this error: What is the right way to override __new__ in an Enum? I have read the docs, but they only show an example where you are subclassing another class as well as Enum: https://docs.python.org/3/library/enum.html#when-to-use-new-vs-init RE: Having trouble writing an Enum with a custom __new__ method - deanhystad - Feb-12-2022 From the docs you referenced: In other words use __new__ when you want to an enum that has a different type of value. Their example used bytes. Your value is a str.class MyEnum(str, Enum): def __new__(cls, value, extra): obj = str.__new__(cls, [value]) obj._value_ = value obj.extra = extra return obj MEMBER = ("This is my enum", 1.5) print(MyEnum.MEMBER) print(MyEnum.MEMBER.value) print(MyEnum.MEMBER.extra) You were trying to create a new enum whose value was your new enum class.
RE: Having trouble writing an Enum with a custom __new__ method - stevendaprano - Feb-13-2022 Thanks deanhystad, but my enums shouldn't be a string subclass. I think I have found a solution thanks to this blog post. from enum import Enum class MyEnum(Enum): MEMBER = ("Hello world", 1.5) def __new__(cls, value, extra): obj = object.__new__(cls) # Don't use super(), use object obj._value_ = value obj.extra = extra return obj RE: Having trouble writing an Enum with a custom __new__ method - deanhystad - Feb-13-2022 Why not? Their value is a string. If I want an enum that has integer values I used use an IntEnum. |