bpo-41816: add StrEnum (GH-22337)

`StrEnum` ensures that its members were already strings, or intended to
be strings.
This commit is contained in:
Ethan Furman 2020-09-21 17:23:13 -07:00 committed by GitHub
parent 68526fe258
commit 0063ff4e58
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 104 additions and 22 deletions

View file

@ -4,7 +4,7 @@ from types import MappingProxyType, DynamicClassAttribute
__all__ = [
'EnumMeta',
'Enum', 'IntEnum', 'Flag', 'IntFlag',
'Enum', 'IntEnum', 'StrEnum', 'Flag', 'IntFlag',
'auto', 'unique',
]
@ -688,7 +688,35 @@ class Enum(metaclass=EnumMeta):
class IntEnum(int, Enum):
"""Enum where members are also (and must be) ints"""
"""
Enum where members are also (and must be) ints
"""
class StrEnum(str, Enum):
"""
Enum where members are also (and must be) strings
"""
def __new__(cls, *values):
if len(values) > 3:
raise TypeError('too many arguments for str(): %r' % (values, ))
if len(values) == 1:
# it must be a string
if not isinstance(values[0], str):
raise TypeError('%r is not a string' % (values[0], ))
if len(values) > 1:
# check that encoding argument is a string
if not isinstance(values[1], str):
raise TypeError('encoding must be a string, not %r' % (values[1], ))
if len(values) > 2:
# check that errors argument is a string
if not isinstance(values[2], str):
raise TypeError('errors must be a string, not %r' % (values[2], ))
value = str(*values)
member = str.__new__(cls, value)
member._value_ = value
return member
def _reduce_ex_by_name(self, proto):