Last active
March 31, 2022 04:11
-
-
Save Ending2015a/0975e04847bd50b42fc5c3df60c717bf to your computer and use it in GitHub Desktop.
This file shows how to use a str type enum in Python
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 Reduction(str, enum.Enum): | |
max = 'max' | |
min = 'min' | |
sum = 'sum' | |
mean = 'mean' | |
prod = 'prod' | |
my_reduction = Reduction.max | |
print(f"My reduction: {my_reduction}") | |
# My reduction: max | |
print(f"My reduction type: {type(my_reduction)}") | |
print(type(my_reduction)) | |
# My reduction type: <enum 'Reduction'> | |
assert my_reduction == Reduction.max | |
assert my_reduction == 'max' | |
assert my_reduction == Reduction('max') | |
assert my_reduction == Reduction(Reduction.max) | |
assert my_reduction != 'min' | |
assert my_reduction != Reduction.min | |
assert my_reduction != Reduction('min') | |
assert my_reduction != Reduction(Reduction.min) | |
from typing import Union | |
def reduce(*args, reduction: Union[str, Reduction]): | |
assert reduction is not None | |
# this line converts str or Reduction to Reduction | |
# and throws an error if it failed. | |
# e.g. ValueError: 'foo' is not a valid Reduction | |
reduction = Reduction(reduction) | |
if reduction == Reduction.max: | |
return max(args) | |
elif reduction == Reduction.min: | |
return min(args) | |
elif reduction == Reduction.sum: | |
return sum(args) | |
else: | |
raise NotImplementedError | |
print(reduce(1, 2, 3, reduction=Reduction.sum)) | |
print(reduce(1, 2, 3, reduction='sum')) | |
try: | |
print(reduce(1, 2, 3, reduction='foo')) | |
except ValueError as e: | |
# ValueError: 'foo' is not a valid Reduction | |
print(f"{type(e).__name__}: {str(e)}") | |
# === string enum with default value === | |
class TestEnum(str, enum.Enum): | |
apple = 'apple' | |
benana = 'benana' | |
@classmethod | |
def _missing_(cls, value): | |
if value is None: | |
return cls.apple | |
assert TestEnum(None) == TestEnum.apple | |
try: | |
TestEnum("cat") | |
except ValueError as e: | |
print(f"{type(e).__name__}: {str(e)}") | |
# ValueError: 'cat' is not a valid TestEnum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment