feat: Implement auto-naming string enum

This commit is contained in:
Paul Harrison 2022-11-18 12:59:18 +00:00
parent 3899da2f52
commit 5efd77728d
4 changed files with 43 additions and 0 deletions

0
poker/utils/__init__.py Normal file
View File

27
poker/utils/enum.py Normal file
View File

@ -0,0 +1,27 @@
from enum import StrEnum
from typing import Any
class AutoName(StrEnum):
"""Use the lower case name as the value for Python Enum (default would be integers).
Inherits from str to ensure all types are string and as a bonus it becomes JSON
serializable.
See here for more information:
https://docs.python.org/3/library/enum.html#using-automatic-values
"""
def __str__(self) -> str:
"""Return string representation."""
return str(self.value)
@staticmethod
def _generate_next_value_(
name: str, start: int, count: int, last_values: list[Any]
) -> str:
"""Enum standard structure - the next value.
See this on @staticmethod: https://github.com/python/mypy/issues/7591
"""
return name.lower()

0
tests/utils/__init__.py Normal file
View File

16
tests/utils/test_enum.py Normal file
View File

@ -0,0 +1,16 @@
from enum import auto
from poker.utils.enum import AutoName
def test_auto_name() -> None:
class Example(AutoName):
"""Example Enum."""
foo = auto()
BAR = auto()
WeIrD = auto()
assert Example.foo.value == "foo"
assert Example.BAR.value == "bar"
assert Example.WeIrD.value == "weird"