Python Forum
Having trouble writing an Enum with a custom __new__ method
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Having trouble writing an Enum with a custom __new__ method
#2
From the docs you referenced:
Output:
When to use __new__() vs. __init__() __new__() must be used whenever you want to customize the actual value of the Enum member. Any other modifications may go in either __new__() or __init__(), with __init__() being preferred.
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)
Output:
MyEnum.MEMBER This is my enum 1.5
You were trying to create a new enum whose value was your new enum class.
stevendaprano likes this post
Reply


Messages In This Thread
RE: Having trouble writing an Enum with a custom __new__ method - by deanhystad - Feb-12-2022, 05:01 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable sorting methods for Enum DataClasses koen 1 856 May-30-2023, 07:31 PM
Last Post: deanhystad
  Custom method to handle exceptions not working as expected gradlon93 3 1,114 Dec-22-2022, 07:12 PM
Last Post: deanhystad
  Alarm system with state, class, enum. Frankduc 0 1,332 May-04-2022, 01:26 PM
Last Post: Frankduc
  Enum help SephMon 3 1,568 Nov-19-2021, 09:39 AM
Last Post: Yoriz
Smile Set 'Time' format cell when writing data to excel and not 'custom' limors 3 6,506 Mar-29-2021, 09:36 PM
Last Post: Larz60+
  Trouble writing over serial EngineerNeil 1 2,711 Apr-07-2019, 08:17 PM
Last Post: j.crater
  enum from typelib Erhy 2 2,210 Jan-26-2019, 05:37 PM
Last Post: Erhy
  Python error? Enum and strings tycarac 3 3,666 Dec-15-2018, 10:39 AM
Last Post: tycarac
  trouble writing to file after while loop Low_Ki_ 21 13,730 Jan-10-2017, 06:44 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020