Python Enum Class

Enum Class

Python Enum class is a set of symbolic names. The number of members of an Enum class are bound to be unique and constant values.

In this tutorial, we shall learn how to create an enum in your Python program, how to define the constants in it, access these constants and the datatypes we can assign.

Create an Enum class

To create an Enum in Python programming language, use syntax of Python Class and Enum class from enum module.

In the following example, we create an Enum class with three named integer constants.

from enum import Enum

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

Access values of Enum class

To access the values of an Enum Class, you cas use the Enum Class name with dot operator followed by the member.

In the following example, we shall access an Enum constant and print its value.

Python Program

from enum import Enum

class Color(Enum):
	RED = 1
	GREEN = 2
	BLUE = 3
	
print(Color.GREEN)
Run Code Copy

Output

Color.GREEN

Information about Enum member

To get more information about the Enum member, use repr() function.

Python Program

from enum import Enum

class Color(Enum):
	RED = 1
	GREEN = 2
	BLUE = 3
	
print(repr(Color.GREEN))
Run Code Copy

Output

<Color.GREEN: 2>

Enum with constants of different datatypes

You can define constants of any datatype in Enum. In the following example, we will define an Enum class with constants belonging to datatypes of Integer, String and Float.

Python Program

from enum import Enum

class Color(Enum):
	RED = 1
	GREEN = '#00FF00'
	BLUE = 14.0

print(repr(Color.RED))	
print(repr(Color.GREEN))
print(repr(Color.BLUE))
Run Code Copy

Output

<Color.RED: 1>
<Color.GREEN: '#00FF00'>
<Color.BLUE: 14.0>

Summary

In this tutorial of Python Examples, we have learned how to create an Enum class, access members of Enum class and get some extra information about Enum class members.

Code copied to clipboard successfully 👍