mirror of
https://github.com/python/cpython.git
synced 2025-12-10 11:00:14 +00:00
bpo-41816: add StrEnum (GH-22337)
`StrEnum` ensures that its members were already strings, or intended to be strings.
This commit is contained in:
parent
68526fe258
commit
0063ff4e58
4 changed files with 104 additions and 22 deletions
32
Lib/enum.py
32
Lib/enum.py
|
|
@ -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):
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue