pythonenums

Convert enum to int in python


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 .


Solution

  • 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)