Getting value of enum on string conversion

PythonPython 3.xEnumsPython 3.4

Python Problem Overview


I have the following enum defined:

from enum import Enum
class D(Enum):
    x = 1
    y = 2

print(D.x)

now the printed value is

D.x

instead, I wanted the enum's value to be print

1

What can be done to achieve this functionality?

Python Solutions


Solution 1 - Python

You are printing the enum object. Use the .value attribute if you wanted just to print that:

print(D.x.value)

See the Programmatic access to enumeration members and their attributes section:

> If you have an enum member and need its name or value: > > >>> > >>> member = Color.red > >>> member.name > 'red' > >>> member.value > 1

You could add a __str__ method to your enum, if all you wanted was to provide a custom string representation:

class D(Enum):
    def __str__(self):
        return str(self.value)

    x = 1
    y = 2

Demo:

>>> from enum import Enum
>>> class D(Enum):
...     def __str__(self):
...         return str(self.value)
...     x = 1
...     y = 2
... 
>>> D.x
<D.x: 1>
>>> print(D.x)
1

Solution 2 - Python

I implemented access using the following

class D(Enum):
    x = 1
    y = 2

    def __str__(self):
        return '%s' % self.value

now I can just do

print(D.x) to get 1 as result.

You can also use self.name in case you wanted to print x instead of 1.

Solution 3 - Python

If you are going to print value using f-string then you can inherit your enum from both Enum and str. For instance:

from enum import Enum


class D(str, Enum):
    x = 1
    y = 2


print(D.x)
print(f"{D.x}")

Outputs:

D.x
1

Solution 4 - Python

The most straightforward dunder method to use is _repr_ instead of _str_ since it will also allow you to print it in that way also in lists.

class D(Enum):
  x = 1
  y = 2

  def __repr__(self):
      return self.value

print([D.x,D.y])
>>> [1, 2]

Solution 5 - Python

In case you want to compare your enum members to Int values, a better way to do it would be to extend IntEnum:

from enum import IntEnum


class D(IntEnum):
    x = 1
    y = 2


print(D.x)

In this way you can compare values of your enum against integers without explicitly calling .value:

>>> D.x == 1
True

For more information you can check this part of the Python docs: Enum comparisons

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVaibhav MishraView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow
Solution 2 - PythonVaibhav MishraView Answer on Stackoverflow
Solution 3 - PythonVlad BezdenView Answer on Stackoverflow
Solution 4 - PythonTomás Gomez PizarroView Answer on Stackoverflow
Solution 5 - PythonJulianView Answer on Stackoverflow