Convert enum to int in python

58,559

Solution 1

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)

Solution 2

Please use IntEnum

from enum import IntEnum

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

int(loggertype.Info)
0

Solution 3

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.

Solution 4

Why don't you just define the values as numbers instead of strings:

class Nationality:
    POLAND = 0
    GERMANY = 1
    FRANCE = 2

If you need to access the two-letter names, you can simply provide a table that maps them. (Or a dictionary that maps the other way, etc.)

Solution 5

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]
   
Share:
58,559
user278618
Author by

user278618

Updated on July 09, 2022

Comments

  • user278618
    user278618 almost 2 years

    I have an enum Nationality:

    class Nationality:
            Poland='PL'
            Germany='DE'
            France='FR'
    

    How can I convert this some enum to int in this or similar way:

    position_of_enum = int(Nationality.Poland)  # here I want to get 0
    

    I know that I can do it if I had code by:

    counter=0
    for member in dir(Nationality):
        if getattr(Nationality, member) == code:
            lookFor = member
            counter += 1
    return counter
    

    but I don't have, and this way looks too big for python. I'm sure that there is something much simpler .

    • e-satis
      e-satis almost 13 years
      A class is not an enum. Therefor you can't compare.
  • user278618
    user278618 almost 13 years
    I'm using this enum to set value of select which is at few sites with different css and language, and only value property is at each site the same. From this select I must select nationality, and values of options are 0,1,2. I use this casting in c#, so this is from I took this idea.
  • user278618
    user278618 almost 13 years
    you miss names of nationality. I must have them
  • Joe Kington
    Joe Kington almost 13 years
    @user278618 - I left them out for brevity. The idea was that you'd use a lookup table of some sort somewhere in your Nationality class. You could just as easily substitute in your class attributes, instead of strings.
  • Regis May
    Regis May over 7 years
    Works great. Thanks a lot!
  • Paulie
    Paulie about 6 years
    Please explain your answer.
  • ac3d912
    ac3d912 about 4 years
    As of Python 3.4, this is the "more correct" answer (or, the guy who created the library, Ethan Furman's answer below).
  • learning2learn
    learning2learn about 3 years
    In the above example you could also import auto, then initialize Warning, Error, Fatal, to auto().