You can make enum
values case insensitive by overriding the Enum
's _missing_
method . As per the documentation, this classmethod—which by default does nothing— can be used to look up for values not found in cls
; thus, allowing one to try and find the enum member by value
.
Note that one could extend from the str
class when declaring the enumeration class (e.g., class MyEnum(str, Enum)
), which would indicate that all members in the enum must have values of the specified type (e.g., str
). This would also allow comparing a string to an enum member (using the equality operator ==
), without having to use the value
attribute on the enum member (e.g., if member.lower() == value
). Otherwise, if the enumeration class was declared as class MyEnum(Enum)
(without str
subclass), one would need to use the value
attribute on the enum member (e.g., if member.value.lower() == value
) to safely compare the enum member to a string.
Also, note that calling the lower()
function on the enum member would not be necessary, unless the enum values of your class include uppercase (or a combination of uppercase and lowercase) letters as well. Hence, for the example below, where only lowercase letters are used, you could avoid using it, and instead simply use if member == value
to compare the enum member to a value; thus, saving you from calling the lower()
funciton on every member in the class.
Example
from enum import Enum
class MyEnum(str, Enum):
ab = 'ab'
cd = 'cd'
@classmethod
def _missing_(cls, value):
value = value.lower()
for member in cls:
if member.lower() == value:
return member
return None
Example (in Python 3.11+)
In Python 3.11+, one could instead use the newly introduced StrEnum
, which allows using the auto()
feature, resulting in the lower-cased version of the member's name as the value.
from enum import StrEnum, auto
class MyEnum(StrEnum):
AB = auto()
CD = auto()
@classmethod
def _missing_(cls, value):
value = value.lower()
for member in cls:
if member == value:
return member
return None