Skip to content

Instantly share code, notes, and snippets.

@clemlesne
Last active February 24, 2025 10:06
Show Gist options
  • Save clemlesne/98b4929d845fd7fc14dc2d3efea58bc0 to your computer and use it in GitHub Desktop.
Save clemlesne/98b4929d845fd7fc14dc2d3efea58bc0 to your computer and use it in GitHub Desktop.
Embed documentation, pretty name, and value, in a native Python enum that can still be serialized with Pydantic.
from enum import StrEnum
def main() -> None:
print(MyEnum.INFRASTRUCTURE_AS_CODE)
print(str(MyEnum.INFRASTRUCTURE_AS_CODE))
print(MyEnum.INFRASTRUCTURE_AS_CODE.__doc__)
class StrEnumWithDocstring(StrEnum):
_display: str | None
def __new__(
cls,
value: str,
display: str | None = None,
doc: str | None = None,
):
self = str.__new__(cls, value)
# Set the value
self._value_ = value
# Set the display
self._display = display
# Set the docstring
if doc is not None:
self.__doc__ = doc
return self
def __str__(self):
return self._display or self.value
class MyEnum(StrEnumWithDocstring):
INFRASTRUCTURE_AS_CODE = (
"infrastructure_as_code",
"Infrastructure as code",
"Use of infrastructure as code (e.g. Terraform, CloudFormation).",
)
POWER_PLATFORM = (
"cloud",
"Cloud platform",
"Use of a cloud platform (e.g. AWS, GCP, Azure).",
)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment