Convert enum to int in python

Using either the enum34 backport or aenum1 you can create a specialized Enum:

# using enum34
from enum import Enum

class Nationality(Enum):

    PL = 0, 'Poland'
    DE = 1, 'Germany'
    FR = 2, 'France'

    def __new__(cls, value, name):
        member = object.__new__(cls)
        member._value_ = value
        member.fullname = name
        return member

    def __int__(self):
        return self.value

and in use:

>>> print(Nationality.PL)
Nationality.PL
>>> print(int(Nationality.PL))
0
>>> print(Nationality.PL.fullname)
'Poland'

The above is more easily written using aenum1:

# using aenum
from aenum import Enum, MultiValue

class Nationality(Enum):
    _init_ = 'value fullname'
    _settings_ = MultiValue

    PL = 0, 'Poland'
    DE = 1, 'Germany'
    FR = 2, 'France'

    def __int__(self):
        return self.value

which has the added functionality of:

>>> Nationality('Poland')
<Nationality.PL: 0>

1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.


from enum import Enum

class Phone(Enum):
    APPLE = 1 #do not write comma (,)
    ANDROID = 2

#as int:
Phone.APPLE.value

Need to access tuple by index if using commas:

class Phone(Enum):
    APPLE = 1, # note: there is comma (,)
    ANDROID = 2,

#as int:
Phone.APPLE.value[0]
   

Please use IntEnum

from enum import IntEnum

class loggertype(IntEnum):
    Info = 0
    Warning = 1
    Error = 2
    Fatal = 3

int(loggertype.Info)
0

There are better (and more "Pythonic") ways of doing what you want.

Either use a tuple (or list if it needs to be modified), where the order will be preserved:

code_lookup = ('PL', 'DE', 'FR')
return code_lookup.index('PL') 

Or use a dictionary along the lines of:

code_lookup = {'PL':0, 'FR':2, 'DE':3}
return code_lookup['PL']  

The latter is preferable, in my opinion, as it's more readable and explicit.

A namedtuple might also be useful, in your specific case, though it's probably overkill:

import collections
Nationalities = collections.namedtuple('Nationalities', 
                                       ['Poland', 'France', 'Germany'])
nat = Nationalities('PL', 'FR', 'DE')
print nat.Poland
print nat.index(nat.Germany)

Tags:

Python

Enums