0

is it good idea to convert enum self.value to string inside of __str__ try to get everyone's opinion if I should add str(self.value) or just self.value to get value from each key in enum. One benefit is force str result as string. so when some stupid engineer put ny = 10234 I can still get string type value

from enum import Enum
class City(Enum):
    def __str__(self):
        return str(self.value)
    ny = 'New York'
    ca = 'New California'
    nj = 'New Jersey'
    RI = 'Rhode Island'
City.RI
jacobcan118
  • 7,797
  • 12
  • 50
  • 95

1 Answers1

0

__str__ must return a str. If you are going to override the default Enum __str__ method, then you must return a str from it.

Also, __str__ should return a nice, human readable string -- something you might drop into text -- not the output from repr(), which should be used for debugging and other low-level tasks.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • correct..but my concern is if I should add str(self.value) to convert whatever value match with key..to avoid the error `__str__ returned non-string (type int)` – jacobcan118 Aug 20 '18 at 18:18
  • 1
    @jacobcan118: if you are overriding `__str__` to return the value of the Enum member, and that value is or may be a non-`str`, then yes, use `str()` on it, or some other method that will convert the value to a `str`. – Ethan Furman Aug 20 '18 at 19:55