Skip to content

Commit

Permalink
Fix ne method for StrEnum.
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 711434175
  • Loading branch information
aslanides authored and The etils Authors committed Jan 2, 2025
1 parent cec372a commit bf0b203
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
3 changes: 3 additions & 0 deletions etils/epy/py_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ def __eq__(self, other: str) -> bool:
return False
return other.lower() == self.value.lower()

def __ne__(self, other: str) -> bool:
return not self.__eq__(other)

def __hash__(self) -> int: # pylint: disable=useless-super-delegation
# Somehow `hash` is not defined automatically (maybe because of
# the `__eq__`, so define it explicitly.
Expand Down
23 changes: 18 additions & 5 deletions etils/epy/py_utils_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,17 @@
import pytest


class MyEnum(epy.StrEnum):
MY_OTHER_ATTR = enum.auto()
MY_ATTR = enum.auto()
MY_UPPER_ATTR = 'My_Upper_Attr'
OTHER = 'not_Other'


def test_str_enum():
if sys.version_info[:2] <= (3, 11):
return # Skip for 3.11

class MyEnum(epy.StrEnum):
MY_OTHER_ATTR = enum.auto()
MY_ATTR = enum.auto()
MY_UPPER_ATTR = 'My_Upper_Attr'
OTHER = 'not_Other'

assert MyEnum.MY_ATTR is MyEnum.MY_ATTR
assert MyEnum('my_attr') is MyEnum.MY_ATTR
Expand Down Expand Up @@ -147,3 +149,14 @@ def __init__(self):
def test_issubclass():
assert not epy.issubclass(1, int)
assert epy.issubclass(bool, int)


def test_equality():
x = MyEnum.MY_ATTR
assert x == 'MY_ATTR'
assert x == 'my_attr'
assert not x != 'MY_ATTR' # pylint: disable=g-comparison-negation
assert not x != 'my_attr' # pylint: disable=g-comparison-negation

assert x != 'MY_OTHER_ATTR'
assert x != MyEnum.MY_OTHER_ATTR

0 comments on commit bf0b203

Please sign in to comment.