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 .
Use the IntEnum class from the enum module to convert an enum to an integer in Python. You can use the auto() class if the exact value is unimportant. To get a value of an enum member, use the value attribute on the member.
By default, the type for enum elements is int. We can set different type by adding a colon like an example below. The different types which can be set are sbyte, byte, short, ushort, uint, ulong, and long.
IntEnum: Base class for creating enumerated constants that are also subclasses of int. it says that members of an IntEnum can be compared to integers; by extension, integer enumerations of different types can also be compared to each other.
Python enums are useful to represent data that represent a finite set of states such as days of the week, months of the year, etc. They were added to Python 3.4 via PEP 435. However, it is available all the way back to 2.4 via pypy. As such, you can expect them to be a staple as you explore Python programming.
Please use IntEnum
from enum import IntEnum class loggertype(IntEnum): Info = 0 Warning = 1 Error = 2 Fatal = 3 int(loggertype.Info) 0
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 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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With