Enum is a built-in Python class that represents a set of named values. An Enum can be thought of as a collection of constants, where each constant has a unique name and value. Enums provide a way to define a set of named values in a clear and concise way, making your code more readable and maintainable. They can also help catch errors early in your development process by ensuring that only valid values are used for a variable or parameter.
The benefits of using Enum in Python include:
- Readability: Enum provides a clear and concise way to define a set of named values in your code, which makes it easier to understand what the values represent.
- Maintainability: By defining a fixed set of values using Enum, you can ensure that only valid values are used for a variable or parameter, which can help catch errors early in your development process.
Here’s an example of defining an Enum:
class Color(Enum):
RED = auto()
GREEN = auto()
BLUE = auto()
class Size(Enum):
SMALL = auto()
MEDIUM = auto()
LARGE = auto()
class Shape(Enum):
SQUARE = auto()
CIRCLE = auto()
TRIANGLE = auto()
class Item:
def __init__(self, name, color, size, shape):
self.name = name
self.color = color
self.size = size
self.shape = shape
def __str__(self):
return f"{self.name} ({self.color.name}, {self.size.name}, {self.shape.name})"
In this example, we have defined three separate enums to represent colors, sizes, and shapes. Each enum has several members defined using the auto()
method, which generates unique values for each member. This is a convenient way to automatically generate values for enum members without having to manually specify the values.
For example, you can see the value for the Color class by running
print(Color.RED.value) # 1
print(Color.GREEN.value) # 2
print(Color.BLUE.value) # 3
We then define a Item
class that takes in a name, color, size, and shape, and creates an object with those attributes. The __str__
method is defined to print out the item's name, color, size, and shape in a readable format.
item1 = Item("Ball", Color.GREEN, Size.MEDIUM, Shape.CIRCLE)
item2 = Item("Cube", Color.RED, Size.SMALL, Shape.SQUARE)
item3 = Item("Pyramid", Color.BLUE, Size.LARGE, Shape.TRIANGLE)
We then create three Item
objects using different combinations of colors, sizes, and shapes. By using enums to represent these attributes, the code becomes more readable, flexible, and maintainable.
For example, if we decide to add a new color like YELLOW
, we can simply add a new member to the Color
enum and all the existing code that uses the enum will automatically be updated to include the new member. This can help make your code more maintainable and less error-prone in the long run.
If you need to have an enum as a string,.name
is a string representation of the enum member.
print(type(Color.RED.name)) #<class 'str'>
You can pass an input string to your enum class, and if it’s not a valid member name, a KeyError
error will be raised. For instance, if you pass the string ED to the Color class, you'll get a KeyError
because ED is not a valid member name of this class. This can help you catch mistakes in your code early and avoid bugs down the line.
f = Color["ED"] #KeyError: 'ED'
f = Color["RED"]
print(f) #Color.RED
print(type(f))#<enum 'Color'>
What happens if you try to change the value of an Enum?
In Python, the values of an Enum are typically treated as constants, and you should generally avoid changing them at runtime. If you try to change the value of an Enum member, you will get an AttributeError at runtime:
Color.RED = 4 # AttributeError: Cannot reassign members.
This is because the Enum members are intended to be immutable and treated as constants.