Skip to content

Instantly share code, notes, and snippets.

@malcolmgreaves
Last active August 30, 2019 22:00
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 malcolmgreaves/302809df3649a9b1c910fca8541e4d5f to your computer and use it in GitHub Desktop.
Save malcolmgreaves/302809df3649a9b1c910fca8541e4d5f to your computer and use it in GitHub Desktop.
Parse a name-serialized enum from a string.
from enum import Enum
from typing import TypeVar, Type
E = TypeVar('E', bound=Enum)
def parse_enum(enum_type: Type[E], enum_name:str) -> E:
try:
for known_e_name, enum_val in enum_type._member_map_.items():
if enum_name == known_e_name:
return enum_val
raise ValueError(f"Could not parse '{enum_name}' into a value of enum '{enum_type}'")
except AttributeError as e:
raise ValueError(f"Is enum type ('{enum_type}') actually an enum?", e)
if __name__ == "__main__":
E1 = Enum('E1', ['a','b','c'])
print(parse_enum(E1, 'a'))
class E2(Enum):
w, x, y, z = range(4)
print(parse_enum(E2, 'w'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment