Python Forum
Return a string or byte object from Enum class?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Return a string or byte object from Enum class?
#1
I wish to have a class that simply contains some values. I want to avoid using the .value attribute. In other words I want to use "class.my_enum" to get a value instead of "class.my_enum.value".

I have the following code that will always return a string.

from enum import Enum

class TestClass(str, Enum):
    str_value = "abc"
    byte_value = "abc".encode('latin-1')
    
    def __str__(self):
        return str.__str__(self.value)
    

x = TestClass.str_value
print(x)
print(type(x))

x = TestClass.byte_value
print(x)
print(type(x))
This returns my values TestClass.str_value and TestClass.byte_value as an enum that works like a string. Unfortunately, I need TestClass.byte_value to be a bytes object.

Something like this would do what I want, except that this would allow the values in the class to be altered.

class TestClass():
    str_value = "abc"
    byte_value = "abc".encode('latin-1')


x = TestClass.str_value
print(x)
print(type(x))

x = TestClass.byte_value
print(x)
print(type(x))

# This should cause an error
TestClass.str_value = 5
print(TestClass.str_value)
How can I return different value types and disallow changing of their values?
Reply


Messages In This Thread
Return a string or byte object from Enum class? - by Calab - May-13-2025, 03:57 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Printing out incidence values for Class Object SquderDragon 3 1,429 Apr-01-2024, 07:52 AM
Last Post: SquderDragon
  This result object does not return rows. It has been closed automatically dawid294 5 5,912 Jan-10-2024, 10:55 PM
Last Post: deanhystad
  error in class: TypeError: 'str' object is not callable akbarza 2 2,014 Dec-30-2023, 04:35 PM
Last Post: deanhystad
  how to return a reference to an object? Skaperen 8 5,523 Jun-07-2023, 05:30 PM
Last Post: Skaperen
  Variable sorting methods for Enum DataClasses koen 1 1,888 May-30-2023, 07:31 PM
Last Post: deanhystad
  Alarm system with state, class, enum. Frankduc 0 2,030 May-04-2022, 01:26 PM
Last Post: Frankduc
Question Having trouble writing an Enum with a custom __new__ method stevendaprano 3 8,494 Feb-13-2022, 06:37 AM
Last Post: deanhystad
  Enum help SephMon 3 2,422 Nov-19-2021, 09:39 AM
Last Post: Yoriz
Exclamation win32com: How to pass a reference object into a COM server class Alfalfa 3 7,081 Jul-26-2021, 06:25 PM
Last Post: Alfalfa
  TypeError: int() argument must be a string, a bytes-like object or a number, not 'Non Anldra12 2 7,930 May-02-2021, 03:45 PM
Last Post: Anldra12

Forum Jump:

User Panel Messages

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