blob: 535c1e3afa0bc918ac1218e5c55f88f4adf49941 [file] [log] [blame]
#!/usr/bin/env python3
#
# Copyright 2023 The Fuchsia Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from enum import Enum
from typing import Type, TypeVar
T = TypeVar("T", bound="StrEnum")
class StrEnum(str, Enum):
def __str__(self) -> str:
if not isinstance(self.value, str):
raise TypeError(f"Expected a str, got {type(self.value)}")
return self.value
@classmethod
def all(cls: Type[T]) -> list[T]:
return [e for e in cls]
@classmethod
def from_str(cls: Type[T], s: str) -> T:
lookup_table = {mode.value: mode for mode in cls.all()}
if s in lookup_table:
return lookup_table[s]
raise TypeError(f'Unknown {cls.__name__} string "{s}"')