Last active
June 9, 2024 23:18
-
-
Save rmasters/c7a97ce426f7dcfbb323b51229b1982d to your computer and use it in GitHub Desktop.
Abusing annotations to add secondary-values to Python StrEnums
This file contains hidden or 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
{% for region in regions|sort %} | |
<label><input type="radio" name="region" value="{{ region.value }}" required> {{ region }}</label> | |
{% endfor %} |
This file contains hidden or 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 typing import Annotation | |
from labelled_enum import LabelledEnum | |
class Region(LabelledEnum): | |
eng: Annotated[str, "England"] = "england" | |
nir: Annotated[str, "Northern Ireland"] = "northern-ireland" | |
sct: Annotated[str, "Scotland"] = "scotland" | |
wls: Annotated[str, "Wales"] = "wales" | |
jinja2_env.render("example.jinja2", {"regions": list(Region)}) |
This file contains hidden or 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 inspect | |
from enum import StrEnum | |
from typing import Annotated, get_args | |
class LabelledEnum(StrEnum): | |
def __str__(self) -> str: | |
annotations = inspect.get_annotations(self.__class__) | |
if self.name in annotations: | |
args = get_args(annotations[self.name]) | |
if args and len(args) == 2: | |
return args[1] | |
return str(self.value) |
This file contains hidden or 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 typing import Annotated | |
from labelled_enum import LabelledEnum | |
def test_labelled_enum(): | |
class TestEnum(LabelledEnum): | |
my_foo: Annotated[str, "Foo"] = "foo" | |
my_bar: str = "bar" | |
my_baz = "baz" | |
assert TestEnum.my_foo.name == "my_foo" | |
assert str(TestEnum.my_foo) == "Foo" | |
assert TestEnum.my_foo.value == "foo" | |
assert TestEnum.my_bar.name == "my_bar" | |
assert str(TestEnum.my_bar) == "bar" | |
assert TestEnum.my_bar.value == "bar" | |
assert TestEnum.my_baz.name == "my_baz" | |
assert str(TestEnum.my_baz) == "baz" | |
assert TestEnum.my_baz.value == "baz" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment