Convert enum to int in python

I have enum Citizenship:

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

How can I convert this enum to int in one way or another:

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

I know I can do this if I had the code:

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

but I don’t have it and this method looks too big for python. I am sure there is something much easier.

+6
source share
5 answers

There are better (and more "pythonic") ways to do what you want.

Use either a tuple (or a list if you need to change it), where the order will be saved:

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

Or use the dictionary line by line:

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

The latter is preferable, in my opinion, more readable and explicit.

A namedtuple may also be useful, in your particular case, although it probably overflows:

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

Using enum34 backport or aenum 1 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 when using:

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

The above is described more easily using aenum 1 :

 # 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 added functionality:

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

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

+8
source

You can not. Python does not preserve the order of class elements, and dir() returns them in any order.

Seeing from your comment that you really need to match strings from integers, you should do just that:

 code_lookup = { 'PL': ("Poland", 0), 'DE': ("Germany", 1), 'FR': ("France", 2), ... } 
+5
source

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 two-letter names, you can simply provide a table that displays them. (Or a dictionary that displays a different path, etc.)

+3
source

I saw something like:

 PL, FR, DE = range(3) 

Wrap it in class and alt, you have a namespace to list.

+3
source

Source: https://habr.com/ru/post/888548/


All Articles