Created
May 5, 2020 01:28
-
-
Save dmyersturnbull/9dea57dd90cedb8d1670664cb50a2970 to your computer and use it in GitHub Desktop.
Python enum with a function for lookup by name.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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