Skip to content

Commit

Permalink
Added to_enum to misc_utils
Browse files Browse the repository at this point in the history
  • Loading branch information
dmichaels-harvard committed Nov 20, 2023
1 parent 471f05b commit a7e50d1
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions dcicutils/misc_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1001,6 +1001,20 @@ def to_boolean(value: str, fallback: Optional[Any]) -> Optional[Any]:
return fallback


def to_enum(value: str, enumerators: List[str]) -> Optional[str]:
matches = []
if isinstance(value, str) and (value := value.strip()) and isinstance(enumerators, List):
enum_specifiers = {str(enum).lower(): enum for enum in enumerators}
if (enum_value := enum_specifiers.get(lower_value := value.lower())) is not None:
return enum_value
for enum_canonical, _ in enum_specifiers.items():
if enum_canonical.startswith(lower_value):
matches.append(enum_canonical)
if len(matches) == 1:
return enum_specifiers[matches[0]]
return enum_specifiers[matches[0]] if len(matches) == 1 else value


@contextlib.contextmanager
def override_environ(**overrides):
"""
Expand Down

0 comments on commit a7e50d1

Please sign in to comment.