xxxxxxxxxx
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
def enum_from_string(enum_type, string):
for enum_value in enum_type:
if enum_value.name.lower() == string.lower():
return enum_value
return None
# Example usage:
color_string = "GREEN"
color_enum = enum_from_string(Color, color_string)
if color_enum:
print(color_enum) # Output: Color.GREEN
else:
print("Invalid color string")
xxxxxxxxxx
import enum
class Color(enum.Enum):
RED = 1
GREEN = 2
BLUE = 3
def get_enum_from_string(enum_type, string):
try:
return enum_type[string.upper()]
except KeyError:
raise ValueError('Invalid enum string')
# Usage example
color_string = 'RED'
color_enum = get_enum_from_string(Color, color_string)
print(color_enum)