Skip to content

Instantly share code, notes, and snippets.

@dmyersturnbull
Created May 5, 2020 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmyersturnbull/9dea57dd90cedb8d1670664cb50a2970 to your computer and use it in GitHub Desktop.
Save dmyersturnbull/9dea57dd90cedb8d1670664cb50a2970 to your computer and use it in GitHub Desktop.
Python enum with a function for lookup by name.
import enum
class SmartEnum(enum.Enum):
"""
An enum with a classmethod `of` that parses a string of the member's name.
"""
@classmethod
def of(cls, v):
"""
Returns the member of this enum class from a string with the member's name,
case-insentive and stripping whitespace.
Will return ``v`` if ``v`` is already an instance of this class.
"""
if isinstance(v, cls):
return v
elif isinstance(v, str):
if v in cls:
return cls[v.upper().strip()]
else:
# in case the names are lowercase
# noinspection PyTypeChecker
for e in cls:
if e.name.lower().strip() == v:
return e
raise LookupError("{} not found in {}".format(v, str(cls)))
else:
raise TypeError(str(type(v)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment