Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing __str__ method for Enum class python

I have an enum class in python using list of strings:

from enum import Enum
myEnum = Enum('myEnum',['typeA',typeB','typeC'])

and I want to add method "str" to this enum class:

def __str__(self):
    return self.name

so that when I use str() function, I only get the 'typeX' part, i.e. the enum part withou class name. e.g.

print(str(myEnum.typeA)) # I want this to print "typeA" instead of "myEnum.typeA"

I do not know how to add the "str" method to this class as it is not class definition? Thanks for your help.

like image 976
Amin Merati Avatar asked Mar 14 '26 08:03

Amin Merati


1 Answers

If this is something you do a lot, you can make your own base Enum class, and then use that in the function calls:

class MyBaseEnum(Enum):
    def __str__(self):
        return self.name

myEnum = MyBaseEnum('myEnum',['typeA','typeB','typeC'])

and in use:

>>> print(myEnum.typeB)
typeB
like image 196
Ethan Furman Avatar answered Mar 16 '26 02:03

Ethan Furman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!