One function

StrEnum in google/etils

The author described this change as Fix StrEnum when invalid value. It counts as a record because the check below fails on the code as it stood at a0b710320 and passes on a72cedc0b, with nothing else changed between the two runs.

Fix saved2022-06-16
Sharing licenceApache-2.0 · LICENSE
Change size+12 2

What the code was meant to do, written into the code itself as a docstring

Like `Enum`, but `enum.auto()` assigns `str` rather than `int`. ``python class MyEnum(epy.StrEnum): SOME_ATTR = enum.auto() OTHER_ATTR = enum.auto() assert MyEnum('some_attr') is MyEnum.SOME_ATTR assert MyEnum.SOME_ATTR == 'some_attr' `` `StrEnum` is case insensitive.

The change

2121
2222 @classmethod
2323 def _missing_(cls, value: str) -> StrEnum:
24- if isinstance(value, str):
24+ if isinstance(value, str) and not value.islower():
2525 return cls(value.lower())
26- return super()._missing_(value)
26+ # Could also add `did you meant yy ?`
27+ all_values = [e.value for e in cls]
28+ raise ValueError(f'{value!r} is not a valid {cls.__qualname__}. '
29+ f'Expected one of {all_values}')
2730
2831 def __eq__(self, other: str) -> bool:
2932 return super().__eq__(other.lower())
3235 # Somehow `hash` is not defined automatically (maybe because of
3336 # the `__eq__`, so define it explicitly.
3437 return super().__hash__()
38+
39+ # Pytype is confused by EnumMeta.__iter__ vs str.__iter__
40+ if typing.TYPE_CHECKING:
41+
42+ @classmethod
43+ def __iter__(cls):
44+ return type(enum.Enum).__iter__(cls)

The check that tells the two apart

failpass·etils/epy/py_utils_test.py::test_str_enum

Check file etils/epy/py_utils_test.py, taken without changes from the fix and copied onto the older code, so the exact same check runs against both versions.

Origin and history

The code before ita0b71032095db14acf6b33516bca6d885fe09e35
Broken version dated2022-06-13
Moduleetils.epy.py_utils
Units changedStrEnum
Fingerprint118c6bd8124a09d1
Checked2026-08-18 by goldset/0.1

Every field above is generated by our program. None of it is written by hand.

Other bugs found in google/etils