Last active
August 30, 2019 22:00
-
-
Save malcolmgreaves/302809df3649a9b1c910fca8541e4d5f to your computer and use it in GitHub Desktop.
Parse a name-serialized enum from a string.
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
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