Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Enum and IntEnum in Python

I came across a code that looked like this:

class State(IntEnum):
    READY = 1
    IN_PROGRESS = 2
    FINISHED = 3
    FAILED = 4

and I came to the conclusion that this State class could inherit the Enum class in the same way.

What does inheriting from IntEnum gives me that inheriting from the regular class Enum won't? What is the difference between them?

like image 384
Yuval Pruss Avatar asked Oct 22 '18 12:10

Yuval Pruss


People also ask

When should I use enum in Python?

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.

Is tuple same enum?

Enum and namedtuple in python as enum and struct in C. In other words, enum s are a way of aliasing values, while namedtuple is a way of encapsulating data by name. The two are not really interchangeable, and you can use enum s as the named values in a namedtuple .

What is Auto () in Python?

With the help of enum. auto() method, we can get the assigned integer value automatically by just using enum. auto() method. Syntax : enum.auto() Automatically assign the integer value to the values of enum class attributes.

How do you create an int enum in Python?

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.


1 Answers

From the python Docs:

Enum: Base class for creating enumerated constants.

and:

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.

look at the below example:

class Shape(IntEnum):
    CIRCLE = 1
    SQUARE = 2

class Color(Enum):
    RED = 1
    GREEN = 2

Shape.CIRCLE == Color.RED
>> False

Shape.CIRCLE == 1
>>True

and they will behave same as an integer:

['a', 'b', 'c'][Shape.CIRCLE]
>> 'b'
like image 82
Mehrdad Pedramfar Avatar answered Oct 13 '22 17:10

Mehrdad Pedramfar