python enum from string

preview_player
Показать описание
Certainly! Enumerations, or enums, in Python are a powerful way to represent a set of named values as symbolic names. They can make your code more readable and maintainable. In this tutorial, we'll explore how to convert strings to enums in Python using the enum module.
Create an Enum class by inheriting from the Enum class. Each enum member is defined as a class attribute.
Here, Color is an enumeration with three members: RED, GREEN, and BLUE, each associated with a string value.
Now, let's create a function that converts a string to the corresponding enum member.
This function takes a string (color_str) as input, converts it to lowercase, and then attempts to create an enum member. If the string doesn't match any enum member, a ValueError is raised.
Now, let's use our enum and conversion function in a sample script:
This script will output:
Using enums in Python can improve code clarity and prevent hard-to-spot errors related to magic strings. The conversion function allows you to seamlessly convert strings to enum members, providing a robust way to work with predefined values in your code.
ChatGPT
Рекомендации по теме