Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integrate StrEnum #38

Merged
merged 4 commits into from
Sep 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/lightning_utilities/core/enums.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from enum import Enum
from typing import Optional


class StrEnum(str, Enum):
"""Type of any enumerator with allowed comparison to string invariant to cases."""

@classmethod
def from_str(cls, value: str) -> Optional["StrEnum"]:
statuses = cls.__members__.keys()
for st in statuses:
if st.lower() == value.lower():
return cls[st]
return None

def __eq__(self, other: object) -> bool:
if isinstance(other, Enum):
other = other.value
return self.value.lower() == str(other).lower()

def __hash__(self) -> int:
# re-enable hashtable so it can be used as a dict key or in a set
# example: set(LightningEnum)
return hash(self.value.lower())
41 changes: 41 additions & 0 deletions tests/unittests/core/test_enums.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from enum import Enum

from lightning_utilities.core.enums import StrEnum


def test_consistency():
class MyEnum(StrEnum):
FOO = "FOO"
BAR = "BAR"
BAZ = "BAZ"
NUM = "32"

# normal equality, case invariant
assert MyEnum.FOO == "FOO"
assert MyEnum.FOO == "foo"

# int support
assert MyEnum.NUM == 32
assert MyEnum.NUM in (32, "32")

# key-based
assert MyEnum.NUM == MyEnum.from_str("num")

# collections
assert MyEnum.BAZ not in ("FOO", "BAR")
assert MyEnum.BAZ in ("FOO", "BAZ")
assert MyEnum.BAZ in ("baz", "FOO")
assert MyEnum.BAZ not in {"BAR", "FOO"}
# hash cannot be case invariant
assert MyEnum.BAZ not in {"BAZ", "FOO"}
assert MyEnum.BAZ in {"baz", "FOO"}


def test_comparison_with_other_enum():
class MyEnum(StrEnum):
FOO = "FOO"

class OtherEnum(Enum):
FOO = 123

assert not MyEnum.FOO.__eq__(OtherEnum.FOO)