Python Forum
Python error? Enum and strings
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python error? Enum and strings
#1
Hi

To get the output 'first' as the printed enum value that I want , I have to use 'value[0]' instead of 'value'.
from enum import Enum

class BadEnum(Enum):
    def __str__(self):
       return self.value[0]

    FIRST = 'first',
    SECOND = 'second'


print(BadEnum.FIRST)
Is this an error in Python Enum code to use 'tuple' and not 'string'? If I use 'self.value' instead of 'self.value[0]', I get:
TypeError: __str__ returned non-string (type tuple)
Reply
#2
I can't reproduce the bug with python 3.5 in Linux.
Reply
#3
Note that you have a comma at the end of line 7. This way first is actually a tuple, not str. Remove the comma and it will work for BadEnum.FIRST
You will not have same error if you try to print BadEnum.SECOND as the code is now
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
Hey buran

Many thanks. You were right. I feel a bit silly having posted such a simple mistake.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to understand strings and lists of strings Konstantin23 2 757 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  Variable sorting methods for Enum DataClasses koen 1 760 May-30-2023, 07:31 PM
Last Post: deanhystad
  Help with Logical error processing List of strings dmc8300 3 1,081 Nov-27-2022, 04:10 PM
Last Post: Larz60+
  Alarm system with state, class, enum. Frankduc 0 1,259 May-04-2022, 01:26 PM
Last Post: Frankduc
  Splitting strings in list of strings jesse68 3 1,757 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
Question Having trouble writing an Enum with a custom __new__ method stevendaprano 3 4,125 Feb-13-2022, 06:37 AM
Last Post: deanhystad
  Enum help SephMon 3 1,494 Nov-19-2021, 09:39 AM
Last Post: Yoriz
  Strange syntax error with f-strings Askic 6 4,180 Oct-16-2020, 10:40 AM
Last Post: Askic
  Finding multiple strings between the two same strings Slither 1 2,511 Jun-05-2019, 09:02 PM
Last Post: Yoriz
  Python: if 'X' in 'Y' but with two similar strings as 'X' DreamingInsanity 6 3,855 Feb-01-2019, 01:28 PM
Last Post: buran

Forum Jump:

User Panel Messages

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