2013-06-14 20:55:46 -03:00
|
|
|
import sys
|
2022-01-17 11:18:13 -04:00
|
|
|
import builtins as bltns
|
2013-09-25 11:14:41 -03:00
|
|
|
from types import MappingProxyType, DynamicClassAttribute
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2015-09-18 02:03:52 -03:00
|
|
|
|
2016-09-11 03:36:59 -03:00
|
|
|
__all__ = [
|
2023-12-05 12:27:36 -04:00
|
|
|
'EnumType', 'EnumMeta', 'EnumDict',
|
2022-01-17 11:18:13 -04:00
|
|
|
'Enum', 'IntEnum', 'StrEnum', 'Flag', 'IntFlag', 'ReprEnum',
|
2022-05-06 04:16:22 -03:00
|
|
|
'auto', 'unique', 'property', 'verify', 'member', 'nonmember',
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
'FlagBoundary', 'STRICT', 'CONFORM', 'EJECT', 'KEEP',
|
2022-01-17 11:18:13 -04:00
|
|
|
'global_flag_repr', 'global_enum_repr', 'global_str', 'global_enum',
|
2021-06-09 13:03:55 -03:00
|
|
|
'EnumCheck', 'CONTINUOUS', 'NAMED_FLAGS', 'UNIQUE',
|
2023-06-08 15:40:15 -03:00
|
|
|
'pickle_by_global_name', 'pickle_by_enum_name',
|
2016-09-11 03:36:59 -03:00
|
|
|
]
|
2013-06-14 20:55:46 -03:00
|
|
|
|
|
|
|
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
# Dummy value for Enum and Flag as there are explicit checks for them
|
|
|
|
# before they have been created.
|
2021-03-31 01:17:26 -03:00
|
|
|
# This is also why there are checks in EnumType like `if Enum is not None`
|
2022-01-17 11:18:13 -04:00
|
|
|
Enum = Flag = EJECT = _stdlib_enums = ReprEnum = None
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
|
2022-05-06 04:16:22 -03:00
|
|
|
class nonmember(object):
|
|
|
|
"""
|
2022-09-20 20:31:05 -03:00
|
|
|
Protects item from becoming an Enum member during class creation.
|
2022-05-06 04:16:22 -03:00
|
|
|
"""
|
|
|
|
def __init__(self, value):
|
|
|
|
self.value = value
|
|
|
|
|
|
|
|
class member(object):
|
|
|
|
"""
|
2022-09-20 20:31:05 -03:00
|
|
|
Forces item to become an Enum member during class creation.
|
2022-05-06 04:16:22 -03:00
|
|
|
"""
|
|
|
|
def __init__(self, value):
|
|
|
|
self.value = value
|
|
|
|
|
2013-09-15 16:34:36 -03:00
|
|
|
def _is_descriptor(obj):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Returns True if obj is a descriptor, False otherwise.
|
|
|
|
"""
|
2013-09-15 16:34:36 -03:00
|
|
|
return (
|
|
|
|
hasattr(obj, '__get__') or
|
|
|
|
hasattr(obj, '__set__') or
|
2020-12-08 16:26:56 -04:00
|
|
|
hasattr(obj, '__delete__')
|
|
|
|
)
|
2013-09-15 16:34:36 -03:00
|
|
|
|
2013-06-14 20:55:46 -03:00
|
|
|
def _is_dunder(name):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Returns True if a __dunder__ name, False otherwise.
|
|
|
|
"""
|
|
|
|
return (
|
|
|
|
len(name) > 4 and
|
2019-03-03 18:09:11 -04:00
|
|
|
name[:2] == name[-2:] == '__' and
|
|
|
|
name[2] != '_' and
|
2020-12-08 16:26:56 -04:00
|
|
|
name[-3] != '_'
|
|
|
|
)
|
2013-06-14 20:55:46 -03:00
|
|
|
|
|
|
|
def _is_sunder(name):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Returns True if a _sunder_ name, False otherwise.
|
|
|
|
"""
|
|
|
|
return (
|
|
|
|
len(name) > 2 and
|
2019-03-03 18:09:11 -04:00
|
|
|
name[0] == name[-1] == '_' and
|
2023-10-16 17:37:54 -03:00
|
|
|
name[1] != '_' and
|
|
|
|
name[-2] != '_'
|
2020-12-08 16:26:56 -04:00
|
|
|
)
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2022-05-06 04:16:22 -03:00
|
|
|
def _is_internal_class(cls_name, obj):
|
|
|
|
# do not use `re` as `re` imports `enum`
|
|
|
|
if not isinstance(obj, type):
|
|
|
|
return False
|
|
|
|
qualname = getattr(obj, '__qualname__', '')
|
|
|
|
s_pattern = cls_name + '.' + getattr(obj, '__name__', '')
|
|
|
|
e_pattern = '.' + s_pattern
|
|
|
|
return qualname == s_pattern or qualname.endswith(e_pattern)
|
|
|
|
|
2020-12-09 21:12:11 -04:00
|
|
|
def _is_private(cls_name, name):
|
|
|
|
# do not use `re` as `re` imports `enum`
|
|
|
|
pattern = '_%s__' % (cls_name, )
|
2021-04-15 10:58:33 -03:00
|
|
|
pat_len = len(pattern)
|
2020-12-09 21:12:11 -04:00
|
|
|
if (
|
2021-04-15 10:58:33 -03:00
|
|
|
len(name) > pat_len
|
2020-12-09 21:12:11 -04:00
|
|
|
and name.startswith(pattern)
|
|
|
|
and (name[-1] != '_' or name[-2] != '_')
|
|
|
|
):
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
def _is_single_bit(num):
|
|
|
|
"""
|
|
|
|
True if only one bit set in num (should be an int)
|
|
|
|
"""
|
|
|
|
if num == 0:
|
|
|
|
return False
|
|
|
|
num &= num - 1
|
|
|
|
return num == 0
|
|
|
|
|
2021-01-13 03:47:57 -04:00
|
|
|
def _make_class_unpicklable(obj):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
2021-01-13 03:47:57 -04:00
|
|
|
Make the given obj un-picklable.
|
|
|
|
|
2021-06-14 23:42:46 -03:00
|
|
|
obj should be either a dictionary, or an Enum
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
2014-02-08 15:36:27 -04:00
|
|
|
def _break_on_call_reduce(self, proto):
|
2013-06-14 20:55:46 -03:00
|
|
|
raise TypeError('%r cannot be pickled' % self)
|
2021-01-13 03:47:57 -04:00
|
|
|
if isinstance(obj, dict):
|
|
|
|
obj['__reduce_ex__'] = _break_on_call_reduce
|
|
|
|
obj['__module__'] = '<unknown>'
|
|
|
|
else:
|
|
|
|
setattr(obj, '__reduce_ex__', _break_on_call_reduce)
|
|
|
|
setattr(obj, '__module__', '<unknown>')
|
2013-06-14 20:55:46 -03:00
|
|
|
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
def _iter_bits_lsb(num):
|
2022-11-08 16:00:19 -04:00
|
|
|
# num must be a positive integer
|
|
|
|
original = num
|
2021-06-09 13:03:55 -03:00
|
|
|
if isinstance(num, Enum):
|
|
|
|
num = num.value
|
2022-11-08 16:00:19 -04:00
|
|
|
if num < 0:
|
|
|
|
raise ValueError('%r is not a positive integer' % original)
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
while num:
|
|
|
|
b = num & (~num + 1)
|
|
|
|
yield b
|
|
|
|
num ^= b
|
|
|
|
|
2021-06-11 06:44:43 -03:00
|
|
|
def show_flag_values(value):
|
|
|
|
return list(_iter_bits_lsb(value))
|
|
|
|
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
def bin(num, max_bits=None):
|
|
|
|
"""
|
|
|
|
Like built-in bin(), except negative values are represented in
|
|
|
|
twos-compliment, and the leading bit always indicates sign
|
|
|
|
(0=positive, 1=negative).
|
|
|
|
|
|
|
|
>>> bin(10)
|
|
|
|
'0b0 1010'
|
|
|
|
>>> bin(~10) # ~10 is -11
|
|
|
|
'0b1 0101'
|
|
|
|
"""
|
|
|
|
|
|
|
|
ceiling = 2 ** (num).bit_length()
|
|
|
|
if num >= 0:
|
2022-01-17 11:18:13 -04:00
|
|
|
s = bltns.bin(num + ceiling).replace('1', '0', 1)
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
else:
|
2022-01-17 11:18:13 -04:00
|
|
|
s = bltns.bin(~num ^ (ceiling - 1) + ceiling)
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
sign = s[:3]
|
|
|
|
digits = s[3:]
|
|
|
|
if max_bits is not None:
|
|
|
|
if len(digits) < max_bits:
|
|
|
|
digits = (sign[-1] * max_bits + digits)[-max_bits:]
|
|
|
|
return "%s %s" % (sign, digits)
|
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
def _dedent(text):
|
|
|
|
"""
|
|
|
|
Like textwrap.dedent. Rewritten because we cannot import textwrap.
|
|
|
|
"""
|
|
|
|
lines = text.split('\n')
|
|
|
|
for i, ch in enumerate(lines[0]):
|
|
|
|
if ch != ' ':
|
|
|
|
break
|
|
|
|
for j, l in enumerate(lines):
|
|
|
|
lines[j] = l[i:]
|
|
|
|
return '\n'.join(lines)
|
|
|
|
|
2024-03-07 17:30:26 -04:00
|
|
|
class _not_given:
|
|
|
|
def __repr__(self):
|
|
|
|
return('<not given>')
|
|
|
|
_not_given = _not_given()
|
|
|
|
|
2022-05-06 04:16:22 -03:00
|
|
|
class _auto_null:
|
|
|
|
def __repr__(self):
|
|
|
|
return '_auto_null'
|
|
|
|
_auto_null = _auto_null()
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
|
2016-09-11 03:36:59 -03:00
|
|
|
class auto:
|
|
|
|
"""
|
|
|
|
Instances are replaced with an appropriate value in Enum class suites.
|
|
|
|
"""
|
2022-11-05 22:01:08 -03:00
|
|
|
def __init__(self, value=_auto_null):
|
|
|
|
self.value = value
|
2016-09-11 03:36:59 -03:00
|
|
|
|
2022-05-06 04:16:22 -03:00
|
|
|
def __repr__(self):
|
|
|
|
return "auto(%r)" % self.value
|
|
|
|
|
2021-01-13 03:47:57 -04:00
|
|
|
class property(DynamicClassAttribute):
|
|
|
|
"""
|
|
|
|
This is a descriptor, used to define attributes that act differently
|
|
|
|
when accessed through an enum member and through an enum class.
|
|
|
|
Instance access is the same as property(), but access to an attribute
|
|
|
|
through the enum class will instead look in the class' _member_map_ for
|
|
|
|
a corresponding enum member.
|
|
|
|
"""
|
|
|
|
|
2022-07-25 15:05:10 -03:00
|
|
|
member = None
|
2023-04-18 20:19:23 -03:00
|
|
|
_attr_type = None
|
|
|
|
_cls_type = None
|
2022-07-25 15:05:10 -03:00
|
|
|
|
2021-01-13 03:47:57 -04:00
|
|
|
def __get__(self, instance, ownerclass=None):
|
|
|
|
if instance is None:
|
2022-07-25 15:05:10 -03:00
|
|
|
if self.member is not None:
|
|
|
|
return self.member
|
|
|
|
else:
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
raise AttributeError(
|
2022-01-17 11:18:13 -04:00
|
|
|
'%r has no attribute %r' % (ownerclass, self.name)
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
)
|
2023-04-18 20:19:23 -03:00
|
|
|
if self.fget is not None:
|
|
|
|
# use previous enum.property
|
|
|
|
return self.fget(instance)
|
|
|
|
elif self._attr_type == 'attr':
|
|
|
|
# look up previous attibute
|
|
|
|
return getattr(self._cls_type, self.name)
|
|
|
|
elif self._attr_type == 'desc':
|
|
|
|
# use previous descriptor
|
|
|
|
return getattr(instance._value_, self.name)
|
|
|
|
# look for a member by this name.
|
|
|
|
try:
|
|
|
|
return ownerclass._member_map_[self.name]
|
|
|
|
except KeyError:
|
|
|
|
raise AttributeError(
|
|
|
|
'%r has no attribute %r' % (ownerclass, self.name)
|
|
|
|
) from None
|
2021-01-13 03:47:57 -04:00
|
|
|
|
|
|
|
def __set__(self, instance, value):
|
2023-04-18 20:19:23 -03:00
|
|
|
if self.fset is not None:
|
2021-01-13 03:47:57 -04:00
|
|
|
return self.fset(instance, value)
|
2023-04-18 20:19:23 -03:00
|
|
|
raise AttributeError(
|
|
|
|
"<enum %r> cannot set attribute %r" % (self.clsname, self.name)
|
|
|
|
)
|
2021-01-13 03:47:57 -04:00
|
|
|
|
|
|
|
def __delete__(self, instance):
|
2023-04-18 20:19:23 -03:00
|
|
|
if self.fdel is not None:
|
2021-01-13 03:47:57 -04:00
|
|
|
return self.fdel(instance)
|
2023-04-18 20:19:23 -03:00
|
|
|
raise AttributeError(
|
|
|
|
"<enum %r> cannot delete attribute %r" % (self.clsname, self.name)
|
|
|
|
)
|
2021-01-13 03:47:57 -04:00
|
|
|
|
|
|
|
def __set_name__(self, ownerclass, name):
|
|
|
|
self.name = name
|
|
|
|
self.clsname = ownerclass.__name__
|
|
|
|
|
|
|
|
|
|
|
|
class _proto_member:
|
|
|
|
"""
|
|
|
|
intermediate step for enum members between class execution and final creation
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, value):
|
|
|
|
self.value = value
|
|
|
|
|
|
|
|
def __set_name__(self, enum_class, member_name):
|
|
|
|
"""
|
|
|
|
convert each quasi-member into an instance of the new enum class
|
|
|
|
"""
|
|
|
|
# first step: remove ourself from enum_class
|
|
|
|
delattr(enum_class, member_name)
|
|
|
|
# second step: create member based on enum_class
|
|
|
|
value = self.value
|
2024-01-17 20:31:00 -04:00
|
|
|
if not isinstance(value, tuple):
|
2021-01-13 03:47:57 -04:00
|
|
|
args = (value, )
|
|
|
|
else:
|
|
|
|
args = value
|
|
|
|
if enum_class._member_type_ is tuple: # special case for tuple enums
|
|
|
|
args = (args, ) # wrap it one more time
|
|
|
|
if not enum_class._use_args_:
|
|
|
|
enum_member = enum_class._new_member_(enum_class)
|
2023-03-31 17:52:31 -03:00
|
|
|
else:
|
|
|
|
enum_member = enum_class._new_member_(enum_class, *args)
|
|
|
|
if not hasattr(enum_member, '_value_'):
|
|
|
|
if enum_class._member_type_ is object:
|
|
|
|
enum_member._value_ = value
|
|
|
|
else:
|
2022-07-17 22:51:04 -03:00
|
|
|
try:
|
|
|
|
enum_member._value_ = enum_class._member_type_(*args)
|
|
|
|
except Exception as exc:
|
2023-03-31 17:52:31 -03:00
|
|
|
new_exc = TypeError(
|
|
|
|
'_value_ not set in __new__, unable to create it'
|
|
|
|
)
|
|
|
|
new_exc.__cause__ = exc
|
|
|
|
raise new_exc
|
2021-01-13 03:47:57 -04:00
|
|
|
value = enum_member._value_
|
|
|
|
enum_member._name_ = member_name
|
|
|
|
enum_member.__objclass__ = enum_class
|
|
|
|
enum_member.__init__(*args)
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
enum_member._sort_order_ = len(enum_class._member_names_)
|
2023-04-13 12:24:33 -03:00
|
|
|
|
|
|
|
if Flag is not None and issubclass(enum_class, Flag):
|
2024-02-19 18:36:11 -04:00
|
|
|
if isinstance(value, int):
|
|
|
|
enum_class._flag_mask_ |= value
|
|
|
|
if _is_single_bit(value):
|
|
|
|
enum_class._singles_mask_ |= value
|
2023-04-13 12:24:33 -03:00
|
|
|
enum_class._all_bits_ = 2 ** ((enum_class._flag_mask_).bit_length()) - 1
|
|
|
|
|
2021-01-13 03:47:57 -04:00
|
|
|
# If another member with the same value was already defined, the
|
|
|
|
# new member becomes an alias to the existing one.
|
2021-10-14 17:59:51 -03:00
|
|
|
try:
|
|
|
|
try:
|
|
|
|
# try to do a fast lookup to avoid the quadratic loop
|
|
|
|
enum_member = enum_class._value2member_map_[value]
|
|
|
|
except TypeError:
|
|
|
|
for name, canonical_member in enum_class._member_map_.items():
|
|
|
|
if canonical_member._value_ == value:
|
|
|
|
enum_member = canonical_member
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
raise KeyError
|
|
|
|
except KeyError:
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
# this could still be an alias if the value is multi-bit and the
|
|
|
|
# class is a flag class
|
|
|
|
if (
|
|
|
|
Flag is None
|
|
|
|
or not issubclass(enum_class, Flag)
|
|
|
|
):
|
|
|
|
# no other instances found, record this member in _member_names_
|
|
|
|
enum_class._member_names_.append(member_name)
|
|
|
|
elif (
|
|
|
|
Flag is not None
|
|
|
|
and issubclass(enum_class, Flag)
|
2024-02-19 18:36:11 -04:00
|
|
|
and isinstance(value, int)
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
and _is_single_bit(value)
|
|
|
|
):
|
|
|
|
# no other instances found, record this member in _member_names_
|
|
|
|
enum_class._member_names_.append(member_name)
|
2023-12-05 12:27:36 -04:00
|
|
|
|
|
|
|
enum_class._add_member_(member_name, enum_member)
|
2021-01-13 03:47:57 -04:00
|
|
|
try:
|
|
|
|
# This may fail if value is not hashable. We can't add the value
|
|
|
|
# to the map, and by-value lookups for this value will be
|
|
|
|
# linear.
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
enum_class._value2member_map_.setdefault(value, enum_member)
|
2021-01-13 03:47:57 -04:00
|
|
|
except TypeError:
|
2021-04-27 17:05:08 -03:00
|
|
|
# keep track of the value in a list so containment checks are quick
|
|
|
|
enum_class._unhashable_values_.append(value)
|
2023-12-05 12:27:36 -04:00
|
|
|
enum_class._unhashable_values_map_.setdefault(member_name, []).append(value)
|
2021-01-13 03:47:57 -04:00
|
|
|
|
2013-09-15 16:34:36 -03:00
|
|
|
|
2023-12-05 12:27:36 -04:00
|
|
|
class EnumDict(dict):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Track enum member order and ensure member names are not reused.
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2021-03-31 01:17:26 -03:00
|
|
|
EnumType will use the names found in self._member_names as the
|
2013-06-14 20:55:46 -03:00
|
|
|
enumeration member names.
|
|
|
|
"""
|
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
2023-12-05 12:27:36 -04:00
|
|
|
self._member_names = {} # use a dict -- faster look-up than a list, and keeps insertion order since 3.7
|
2016-09-11 03:36:59 -03:00
|
|
|
self._last_values = []
|
2018-01-22 11:56:37 -04:00
|
|
|
self._ignore = []
|
2020-04-28 14:20:55 -03:00
|
|
|
self._auto_called = False
|
2013-06-14 20:55:46 -03:00
|
|
|
|
|
|
|
def __setitem__(self, key, value):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Changes anything not dundered or not a descriptor.
|
2013-06-14 20:55:46 -03:00
|
|
|
|
|
|
|
If an enum member name is used twice, an error is raised; duplicate
|
|
|
|
values are not checked for.
|
|
|
|
|
|
|
|
Single underscore (sunder) names are reserved.
|
|
|
|
"""
|
2020-12-09 21:12:11 -04:00
|
|
|
if _is_private(self._cls_name, key):
|
2023-05-22 22:59:40 -03:00
|
|
|
# do nothing, name will be a normal attribute
|
2020-12-09 21:12:11 -04:00
|
|
|
pass
|
|
|
|
elif _is_sunder(key):
|
2016-08-31 04:12:15 -03:00
|
|
|
if key not in (
|
2021-04-15 10:49:54 -03:00
|
|
|
'_order_',
|
2022-01-17 11:18:13 -04:00
|
|
|
'_generate_next_value_', '_numeric_repr_', '_missing_', '_ignore_',
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
'_iter_member_', '_iter_member_by_value_', '_iter_member_by_def_',
|
2023-12-05 12:27:36 -04:00
|
|
|
'_add_alias_', '_add_value_alias_',
|
2016-08-31 04:12:15 -03:00
|
|
|
):
|
2020-12-08 16:26:56 -04:00
|
|
|
raise ValueError(
|
|
|
|
'_sunder_ names, such as %r, are reserved for future Enum use'
|
|
|
|
% (key, )
|
|
|
|
)
|
2016-09-11 03:36:59 -03:00
|
|
|
if key == '_generate_next_value_':
|
2020-04-28 14:20:55 -03:00
|
|
|
# check if members already defined as auto()
|
|
|
|
if self._auto_called:
|
|
|
|
raise TypeError("_generate_next_value_ must be defined before members")
|
2021-03-31 01:17:26 -03:00
|
|
|
_gnv = value.__func__ if isinstance(value, staticmethod) else value
|
|
|
|
setattr(self, '_generate_next_value', _gnv)
|
2018-01-22 11:56:37 -04:00
|
|
|
elif key == '_ignore_':
|
|
|
|
if isinstance(value, str):
|
|
|
|
value = value.replace(',',' ').split()
|
|
|
|
else:
|
|
|
|
value = list(value)
|
|
|
|
self._ignore = value
|
|
|
|
already = set(value) & set(self._member_names)
|
|
|
|
if already:
|
2020-12-08 16:26:56 -04:00
|
|
|
raise ValueError(
|
|
|
|
'_ignore_ cannot specify already set names: %r'
|
|
|
|
% (already, )
|
|
|
|
)
|
2013-09-15 16:34:36 -03:00
|
|
|
elif _is_dunder(key):
|
2016-08-20 11:19:31 -03:00
|
|
|
if key == '__order__':
|
|
|
|
key = '_order_'
|
2013-09-15 16:34:36 -03:00
|
|
|
elif key in self._member_names:
|
|
|
|
# descriptor overwriting an enum?
|
2022-01-17 11:18:13 -04:00
|
|
|
raise TypeError('%r already defined as %r' % (key, self[key]))
|
2018-01-22 11:56:37 -04:00
|
|
|
elif key in self._ignore:
|
|
|
|
pass
|
2022-05-06 04:16:22 -03:00
|
|
|
elif isinstance(value, nonmember):
|
|
|
|
# unwrap value here; it won't be processed by the below `else`
|
|
|
|
value = value.value
|
|
|
|
elif _is_descriptor(value):
|
|
|
|
pass
|
2023-05-22 22:59:40 -03:00
|
|
|
elif _is_internal_class(self._cls_name, value):
|
|
|
|
# do nothing, name will be a normal attribute
|
|
|
|
pass
|
2022-05-06 04:16:22 -03:00
|
|
|
else:
|
2013-09-15 16:34:36 -03:00
|
|
|
if key in self:
|
|
|
|
# enum overwriting a descriptor?
|
2022-01-17 11:18:13 -04:00
|
|
|
raise TypeError('%r already defined as %r' % (key, self[key]))
|
2022-05-06 04:16:22 -03:00
|
|
|
elif isinstance(value, member):
|
|
|
|
# unwrap value here -- it will become a member
|
|
|
|
value = value.value
|
2022-11-05 22:01:08 -03:00
|
|
|
non_auto_store = True
|
|
|
|
single = False
|
2016-09-11 03:36:59 -03:00
|
|
|
if isinstance(value, auto):
|
2022-11-05 22:01:08 -03:00
|
|
|
single = True
|
|
|
|
value = (value, )
|
gh-114071: [Enum] update docs and code for tuples/subclasses (GH-114871)
Update documentation with `__new__` and `__init__` entries.
Support use of `auto()` in tuple subclasses on member assignment lines. Previously, auto() was only supported on the member definition line either solo or as part of a tuple:
RED = auto()
BLUE = auto(), 'azul'
However, since Python itself supports using tuple subclasses where tuples are expected, e.g.:
from collections import namedtuple
T = namedtuple('T', 'first second third')
def test(one, two, three):
print(one, two, three)
test(*T(4, 5, 6))
# 4 5 6
it made sense to also support tuple subclasses in enum definitions.
2024-02-04 11:22:55 -04:00
|
|
|
if isinstance(value, tuple) and any(isinstance(v, auto) for v in value):
|
2022-12-08 02:58:08 -04:00
|
|
|
# insist on an actual tuple, no subclasses, in keeping with only supporting
|
|
|
|
# top-level auto() usage (not contained in any other data structure)
|
2022-11-05 22:01:08 -03:00
|
|
|
auto_valued = []
|
gh-114071: [Enum] update docs and code for tuples/subclasses (GH-114871)
Update documentation with `__new__` and `__init__` entries.
Support use of `auto()` in tuple subclasses on member assignment lines. Previously, auto() was only supported on the member definition line either solo or as part of a tuple:
RED = auto()
BLUE = auto(), 'azul'
However, since Python itself supports using tuple subclasses where tuples are expected, e.g.:
from collections import namedtuple
T = namedtuple('T', 'first second third')
def test(one, two, three):
print(one, two, three)
test(*T(4, 5, 6))
# 4 5 6
it made sense to also support tuple subclasses in enum definitions.
2024-02-04 11:22:55 -04:00
|
|
|
t = type(value)
|
2022-11-05 22:01:08 -03:00
|
|
|
for v in value:
|
|
|
|
if isinstance(v, auto):
|
|
|
|
non_auto_store = False
|
|
|
|
if v.value == _auto_null:
|
|
|
|
v.value = self._generate_next_value(
|
|
|
|
key, 1, len(self._member_names), self._last_values[:],
|
|
|
|
)
|
|
|
|
self._auto_called = True
|
|
|
|
v = v.value
|
|
|
|
self._last_values.append(v)
|
|
|
|
auto_valued.append(v)
|
|
|
|
if single:
|
|
|
|
value = auto_valued[0]
|
|
|
|
else:
|
gh-114071: [Enum] update docs and code for tuples/subclasses (GH-114871)
Update documentation with `__new__` and `__init__` entries.
Support use of `auto()` in tuple subclasses on member assignment lines. Previously, auto() was only supported on the member definition line either solo or as part of a tuple:
RED = auto()
BLUE = auto(), 'azul'
However, since Python itself supports using tuple subclasses where tuples are expected, e.g.:
from collections import namedtuple
T = namedtuple('T', 'first second third')
def test(one, two, three):
print(one, two, three)
test(*T(4, 5, 6))
# 4 5 6
it made sense to also support tuple subclasses in enum definitions.
2024-02-04 11:22:55 -04:00
|
|
|
try:
|
|
|
|
# accepts iterable as multiple arguments?
|
|
|
|
value = t(auto_valued)
|
|
|
|
except TypeError:
|
|
|
|
# then pass them in singlely
|
|
|
|
value = t(*auto_valued)
|
2021-10-14 17:59:51 -03:00
|
|
|
self._member_names[key] = None
|
2022-11-05 22:01:08 -03:00
|
|
|
if non_auto_store:
|
|
|
|
self._last_values.append(value)
|
2013-06-14 20:55:46 -03:00
|
|
|
super().__setitem__(key, value)
|
|
|
|
|
2023-12-05 12:27:36 -04:00
|
|
|
@property
|
|
|
|
def member_names(self):
|
|
|
|
return list(self._member_names)
|
|
|
|
|
2020-12-10 17:07:00 -04:00
|
|
|
def update(self, members, **more_members):
|
|
|
|
try:
|
|
|
|
for name in members.keys():
|
|
|
|
self[name] = members[name]
|
|
|
|
except AttributeError:
|
|
|
|
for name, value in members:
|
|
|
|
self[name] = value
|
|
|
|
for name, value in more_members.items():
|
|
|
|
self[name] = value
|
|
|
|
|
2023-12-05 12:27:36 -04:00
|
|
|
_EnumDict = EnumDict # keep private name for backwards compatibility
|
|
|
|
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2021-03-31 01:17:26 -03:00
|
|
|
class EnumType(type):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Metaclass for Enum
|
|
|
|
"""
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
|
2013-06-14 20:55:46 -03:00
|
|
|
@classmethod
|
2020-12-24 14:05:02 -04:00
|
|
|
def __prepare__(metacls, cls, bases, **kwds):
|
2020-09-16 11:11:57 -03:00
|
|
|
# check that previous enum members do not exist
|
2022-01-17 11:18:13 -04:00
|
|
|
metacls._check_for_existing_members_(cls, bases)
|
2016-08-31 04:12:15 -03:00
|
|
|
# create the namespace dict
|
2023-12-05 12:27:36 -04:00
|
|
|
enum_dict = EnumDict()
|
2020-12-09 21:12:11 -04:00
|
|
|
enum_dict._cls_name = cls
|
2016-08-31 04:12:15 -03:00
|
|
|
# inherit previous flags and _generate_next_value_ function
|
2020-09-16 11:11:57 -03:00
|
|
|
member_type, first_enum = metacls._get_mixins_(cls, bases)
|
2016-08-31 04:12:15 -03:00
|
|
|
if first_enum is not None:
|
2020-12-08 16:26:56 -04:00
|
|
|
enum_dict['_generate_next_value_'] = getattr(
|
|
|
|
first_enum, '_generate_next_value_', None,
|
|
|
|
)
|
2016-08-31 04:12:15 -03:00
|
|
|
return enum_dict
|
2016-08-20 04:00:52 -03:00
|
|
|
|
2021-04-21 14:20:44 -03:00
|
|
|
def __new__(metacls, cls, bases, classdict, *, boundary=None, _simple=False, **kwds):
|
2013-06-14 20:55:46 -03:00
|
|
|
# an Enum class is final once enumeration items have been defined; it
|
|
|
|
# cannot be mixed with other types (int, float, etc.) if it has an
|
|
|
|
# inherited __new__ unless a new __new__ is defined (or the resulting
|
|
|
|
# class will fail).
|
2018-01-22 11:56:37 -04:00
|
|
|
#
|
2021-04-21 14:20:44 -03:00
|
|
|
if _simple:
|
|
|
|
return super().__new__(metacls, cls, bases, classdict, **kwds)
|
2022-01-17 11:18:13 -04:00
|
|
|
#
|
|
|
|
# remove any keys listed in _ignore_
|
2018-01-22 11:56:37 -04:00
|
|
|
classdict.setdefault('_ignore_', []).append('_ignore_')
|
|
|
|
ignore = classdict['_ignore_']
|
|
|
|
for key in ignore:
|
|
|
|
classdict.pop(key, None)
|
2021-01-13 03:47:57 -04:00
|
|
|
#
|
|
|
|
# grab member names
|
|
|
|
member_names = classdict._member_names
|
|
|
|
#
|
2013-06-14 20:55:46 -03:00
|
|
|
# check for illegal enum names (any others?)
|
2021-01-13 03:47:57 -04:00
|
|
|
invalid_names = set(member_names) & {'mro', ''}
|
2013-06-14 20:55:46 -03:00
|
|
|
if invalid_names:
|
2022-05-23 15:21:58 -03:00
|
|
|
raise ValueError('invalid enum member name(s) %s' % (
|
|
|
|
','.join(repr(n) for n in invalid_names)
|
|
|
|
))
|
2021-01-13 03:47:57 -04:00
|
|
|
#
|
|
|
|
# adjust the sunders
|
|
|
|
_order_ = classdict.pop('_order_', None)
|
2023-03-27 20:25:19 -03:00
|
|
|
_gnv = classdict.get('_generate_next_value_')
|
|
|
|
if _gnv is not None and type(_gnv) is not staticmethod:
|
|
|
|
_gnv = staticmethod(_gnv)
|
2021-01-13 03:47:57 -04:00
|
|
|
# convert to normal dict
|
|
|
|
classdict = dict(classdict.items())
|
2023-03-27 20:25:19 -03:00
|
|
|
if _gnv is not None:
|
|
|
|
classdict['_generate_next_value_'] = _gnv
|
2021-01-13 03:47:57 -04:00
|
|
|
#
|
|
|
|
# data type of member and the controlling Enum class
|
|
|
|
member_type, first_enum = metacls._get_mixins_(cls, bases)
|
|
|
|
__new__, save_new, use_args = metacls._find_new_(
|
|
|
|
classdict, member_type, first_enum,
|
|
|
|
)
|
|
|
|
classdict['_new_member_'] = __new__
|
|
|
|
classdict['_use_args_'] = use_args
|
|
|
|
#
|
|
|
|
# convert future enum members into temporary _proto_members
|
|
|
|
for name in member_names:
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
value = classdict[name]
|
|
|
|
classdict[name] = _proto_member(value)
|
2021-01-13 03:47:57 -04:00
|
|
|
#
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
# house-keeping structures
|
2021-01-13 03:47:57 -04:00
|
|
|
classdict['_member_names_'] = []
|
|
|
|
classdict['_member_map_'] = {}
|
|
|
|
classdict['_value2member_map_'] = {}
|
2021-04-27 17:05:08 -03:00
|
|
|
classdict['_unhashable_values_'] = []
|
2023-12-05 12:27:36 -04:00
|
|
|
classdict['_unhashable_values_map_'] = {}
|
2021-01-13 03:47:57 -04:00
|
|
|
classdict['_member_type_'] = member_type
|
2022-01-17 11:18:13 -04:00
|
|
|
# now set the __repr__ for the value
|
|
|
|
classdict['_value_repr_'] = metacls._find_data_repr_(cls, bases)
|
2021-01-13 03:47:57 -04:00
|
|
|
#
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
# Flag structures (will be removed if final class is not a Flag
|
|
|
|
classdict['_boundary_'] = (
|
|
|
|
boundary
|
|
|
|
or getattr(first_enum, '_boundary_', None)
|
|
|
|
)
|
2023-04-13 12:24:33 -03:00
|
|
|
classdict['_flag_mask_'] = 0
|
|
|
|
classdict['_singles_mask_'] = 0
|
|
|
|
classdict['_all_bits_'] = 0
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
classdict['_inverted_'] = None
|
2021-01-13 03:47:57 -04:00
|
|
|
try:
|
|
|
|
exc = None
|
2024-02-28 19:17:49 -04:00
|
|
|
classdict['_%s__in_progress' % cls] = True
|
2021-01-13 03:47:57 -04:00
|
|
|
enum_class = super().__new__(metacls, cls, bases, classdict, **kwds)
|
2024-02-28 19:17:49 -04:00
|
|
|
classdict['_%s__in_progress' % cls] = False
|
|
|
|
delattr(enum_class, '_%s__in_progress' % cls)
|
2023-11-29 00:40:12 -04:00
|
|
|
except Exception as e:
|
|
|
|
# since 3.12 the line "Error calling __set_name__ on '_proto_member' instance ..."
|
|
|
|
# is tacked on to the error instead of raising a RuntimeError
|
|
|
|
# recreate the exception to discard
|
|
|
|
exc = type(e)(str(e))
|
|
|
|
exc.__cause__ = e.__cause__
|
|
|
|
exc.__context__ = e.__context__
|
|
|
|
tb = e.__traceback__
|
2021-01-13 03:47:57 -04:00
|
|
|
if exc is not None:
|
2023-11-29 00:40:12 -04:00
|
|
|
raise exc.with_traceback(tb)
|
2021-01-13 03:47:57 -04:00
|
|
|
#
|
2022-01-17 11:18:13 -04:00
|
|
|
# update classdict with any changes made by __init_subclass__
|
|
|
|
classdict.update(enum_class.__dict__)
|
|
|
|
#
|
2013-06-14 20:55:46 -03:00
|
|
|
# double check that repr and friends are not the mixin's or various
|
|
|
|
# things break (such as pickle)
|
2020-09-15 20:28:25 -03:00
|
|
|
# however, if the method is defined in the Enum itself, don't replace
|
|
|
|
# it
|
2022-01-17 11:18:13 -04:00
|
|
|
#
|
|
|
|
# Also, special handling for ReprEnum
|
|
|
|
if ReprEnum is not None and ReprEnum in bases:
|
|
|
|
if member_type is object:
|
|
|
|
raise TypeError(
|
|
|
|
'ReprEnum subclasses must be mixed with a data type (i.e.'
|
|
|
|
' int, str, float, etc.)'
|
|
|
|
)
|
|
|
|
if '__format__' not in classdict:
|
|
|
|
enum_class.__format__ = member_type.__format__
|
|
|
|
classdict['__format__'] = enum_class.__format__
|
|
|
|
if '__str__' not in classdict:
|
|
|
|
method = member_type.__str__
|
|
|
|
if method is object.__str__:
|
|
|
|
# if member_type does not define __str__, object.__str__ will use
|
|
|
|
# its __repr__ instead, so we'll also use its __repr__
|
|
|
|
method = member_type.__repr__
|
|
|
|
enum_class.__str__ = method
|
|
|
|
classdict['__str__'] = enum_class.__str__
|
2014-02-18 16:37:12 -04:00
|
|
|
for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'):
|
2022-01-17 11:18:13 -04:00
|
|
|
if name not in classdict:
|
2022-07-17 22:51:04 -03:00
|
|
|
# check for mixin overrides before replacing
|
|
|
|
enum_method = getattr(first_enum, name)
|
|
|
|
found_method = getattr(enum_class, name)
|
|
|
|
object_method = getattr(object, name)
|
|
|
|
data_type_method = getattr(member_type, name)
|
|
|
|
if found_method in (data_type_method, object_method):
|
|
|
|
setattr(enum_class, name, enum_method)
|
2021-01-13 03:47:57 -04:00
|
|
|
#
|
2022-01-22 22:27:52 -04:00
|
|
|
# for Flag, add __or__, __and__, __xor__, and __invert__
|
|
|
|
if Flag is not None and issubclass(enum_class, Flag):
|
|
|
|
for name in (
|
|
|
|
'__or__', '__and__', '__xor__',
|
|
|
|
'__ror__', '__rand__', '__rxor__',
|
|
|
|
'__invert__'
|
|
|
|
):
|
|
|
|
if name not in classdict:
|
|
|
|
enum_method = getattr(Flag, name)
|
|
|
|
setattr(enum_class, name, enum_method)
|
|
|
|
classdict[name] = enum_method
|
|
|
|
#
|
2013-06-14 20:55:46 -03:00
|
|
|
# replace any other __new__ with our own (as long as Enum is not None,
|
|
|
|
# anyway) -- again, this is to support pickle
|
|
|
|
if Enum is not None:
|
|
|
|
# if the user defined their own __new__, save it before it gets
|
|
|
|
# clobbered in case they subclass later
|
|
|
|
if save_new:
|
|
|
|
enum_class.__new_member__ = __new__
|
|
|
|
enum_class.__new__ = Enum.__new__
|
2021-01-13 03:47:57 -04:00
|
|
|
#
|
2016-08-20 11:19:31 -03:00
|
|
|
# py3 support for definition order (helps keep py2/py3 code in sync)
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
#
|
|
|
|
# _order_ checking is spread out into three/four steps
|
|
|
|
# - if enum_class is a Flag:
|
|
|
|
# - remove any non-single-bit flags from _order_
|
|
|
|
# - remove any aliases from _order_
|
|
|
|
# - check that _order_ and _member_names_ match
|
|
|
|
#
|
|
|
|
# step 1: ensure we have a list
|
2016-08-20 11:19:31 -03:00
|
|
|
if _order_ is not None:
|
|
|
|
if isinstance(_order_, str):
|
|
|
|
_order_ = _order_.replace(',', ' ').split()
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
#
|
|
|
|
# remove Flag structures if final class is not a Flag
|
|
|
|
if (
|
|
|
|
Flag is None and cls != 'Flag'
|
|
|
|
or Flag is not None and not issubclass(enum_class, Flag)
|
|
|
|
):
|
|
|
|
delattr(enum_class, '_boundary_')
|
|
|
|
delattr(enum_class, '_flag_mask_')
|
2023-04-13 12:24:33 -03:00
|
|
|
delattr(enum_class, '_singles_mask_')
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
delattr(enum_class, '_all_bits_')
|
|
|
|
delattr(enum_class, '_inverted_')
|
|
|
|
elif Flag is not None and issubclass(enum_class, Flag):
|
|
|
|
# set correct __iter__
|
|
|
|
member_list = [m._value_ for m in enum_class]
|
|
|
|
if member_list != sorted(member_list):
|
|
|
|
enum_class._iter_member_ = enum_class._iter_member_by_def_
|
|
|
|
if _order_:
|
|
|
|
# _order_ step 2: remove any items from _order_ that are not single-bit
|
|
|
|
_order_ = [
|
|
|
|
o
|
|
|
|
for o in _order_
|
|
|
|
if o not in enum_class._member_map_ or _is_single_bit(enum_class[o]._value_)
|
|
|
|
]
|
|
|
|
#
|
|
|
|
if _order_:
|
|
|
|
# _order_ step 3: remove aliases from _order_
|
|
|
|
_order_ = [
|
|
|
|
o
|
|
|
|
for o in _order_
|
|
|
|
if (
|
|
|
|
o not in enum_class._member_map_
|
|
|
|
or
|
|
|
|
(o in enum_class._member_map_ and o in enum_class._member_names_)
|
|
|
|
)]
|
|
|
|
# _order_ step 4: verify that _order_ and _member_names_ match
|
2016-08-20 11:19:31 -03:00
|
|
|
if _order_ != enum_class._member_names_:
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
raise TypeError(
|
2022-01-17 11:18:13 -04:00
|
|
|
'member order does not match _order_:\n %r\n %r'
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
% (enum_class._member_names_, _order_)
|
|
|
|
)
|
2022-12-16 16:30:47 -04:00
|
|
|
#
|
2013-06-14 20:55:46 -03:00
|
|
|
return enum_class
|
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
def __bool__(cls):
|
2016-04-14 03:52:09 -03:00
|
|
|
"""
|
|
|
|
classes/types should always be True.
|
|
|
|
"""
|
|
|
|
return True
|
|
|
|
|
2024-03-07 17:30:26 -04:00
|
|
|
def __call__(cls, value, names=_not_given, *values, module=None, qualname=None, type=None, start=1, boundary=None):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Either returns an existing member, or creates a new enum class.
|
2013-06-14 20:55:46 -03:00
|
|
|
|
|
|
|
This method is used both when an enum class is given a value to match
|
|
|
|
to an enumeration member (i.e. Color(3)) and for the functional API
|
2016-11-21 13:22:05 -04:00
|
|
|
(i.e. Color = Enum('Color', names='RED GREEN BLUE')).
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2022-11-15 12:49:22 -04:00
|
|
|
The value lookup branch is chosen if the enum is final.
|
|
|
|
|
2014-03-03 16:42:52 -04:00
|
|
|
When used for the functional API:
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2014-03-03 16:42:52 -04:00
|
|
|
`value` will be the name of the new class.
|
|
|
|
|
|
|
|
`names` should be either a string of white-space/comma delimited names
|
2014-09-17 00:35:55 -03:00
|
|
|
(values will start at `start`), or an iterator/mapping of name, value pairs.
|
2014-03-03 16:42:52 -04:00
|
|
|
|
|
|
|
`module` should be set to the module this class is being created in;
|
|
|
|
if it is not set, an attempt to find that module will be made, but if
|
|
|
|
it fails the class will not be picklable.
|
|
|
|
|
|
|
|
`qualname` should be set to the actual location this class can be found
|
|
|
|
at in its module; by default it is set to the global scope. If this is
|
|
|
|
not correct, unpickling will fail in some circumstances.
|
|
|
|
|
|
|
|
`type`, if set, will be mixed in as the first base class.
|
2013-06-14 20:55:46 -03:00
|
|
|
"""
|
2022-11-15 12:49:22 -04:00
|
|
|
if cls._member_map_:
|
|
|
|
# simple value lookup if members exist
|
2024-03-07 17:30:26 -04:00
|
|
|
if names is not _not_given:
|
2022-11-15 12:49:22 -04:00
|
|
|
value = (value, names) + values
|
2013-06-14 20:55:46 -03:00
|
|
|
return cls.__new__(cls, value)
|
|
|
|
# otherwise, functional API: we're creating a new Enum type
|
2024-03-07 17:30:26 -04:00
|
|
|
if names is _not_given and type is None:
|
2023-09-07 22:19:03 -03:00
|
|
|
# no body? no data-type? possibly wrong usage
|
|
|
|
raise TypeError(
|
|
|
|
f"{cls} has no members; specify `names=()` if you meant to create a new, empty, enum"
|
|
|
|
)
|
2020-12-08 16:26:56 -04:00
|
|
|
return cls._create_(
|
2022-11-15 12:49:22 -04:00
|
|
|
class_name=value,
|
2024-03-11 17:42:01 -03:00
|
|
|
names=None if names is _not_given else names,
|
2020-12-08 16:26:56 -04:00
|
|
|
module=module,
|
|
|
|
qualname=qualname,
|
|
|
|
type=type,
|
|
|
|
start=start,
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
boundary=boundary,
|
2020-12-08 16:26:56 -04:00
|
|
|
)
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2022-06-22 04:04:04 -03:00
|
|
|
def __contains__(cls, value):
|
|
|
|
"""Return True if `value` is in `cls`.
|
2022-01-17 11:18:13 -04:00
|
|
|
|
2022-06-22 04:04:04 -03:00
|
|
|
`value` is in `cls` if:
|
|
|
|
1) `value` is a member of `cls`, or
|
|
|
|
2) `value` is the value of one of the `cls`'s members.
|
2022-01-17 11:18:13 -04:00
|
|
|
"""
|
2022-06-22 04:04:04 -03:00
|
|
|
if isinstance(value, cls):
|
|
|
|
return True
|
2023-12-05 12:27:36 -04:00
|
|
|
try:
|
|
|
|
return value in cls._value2member_map_
|
|
|
|
except TypeError:
|
|
|
|
return value in cls._unhashable_values_
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2013-09-22 20:18:19 -03:00
|
|
|
def __delattr__(cls, attr):
|
|
|
|
# nicer error message when someone tries to delete an attribute
|
|
|
|
# (see issue19025).
|
|
|
|
if attr in cls._member_map_:
|
2022-01-17 11:18:13 -04:00
|
|
|
raise AttributeError("%r cannot delete member %r." % (cls.__name__, attr))
|
2013-09-22 20:18:19 -03:00
|
|
|
super().__delattr__(attr)
|
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
def __dir__(cls):
|
2022-01-18 19:13:13 -04:00
|
|
|
interesting = set([
|
|
|
|
'__class__', '__contains__', '__doc__', '__getitem__',
|
|
|
|
'__iter__', '__len__', '__members__', '__module__',
|
|
|
|
'__name__', '__qualname__',
|
|
|
|
]
|
|
|
|
+ cls._member_names_
|
|
|
|
)
|
|
|
|
if cls._new_member_ is not object.__new__:
|
|
|
|
interesting.add('__new__')
|
|
|
|
if cls.__init_subclass__ is not object.__init_subclass__:
|
|
|
|
interesting.add('__init_subclass__')
|
2022-01-17 11:18:13 -04:00
|
|
|
if cls._member_type_ is object:
|
2022-01-18 19:13:13 -04:00
|
|
|
return sorted(interesting)
|
2022-01-17 11:18:13 -04:00
|
|
|
else:
|
|
|
|
# return whatever mixed-in data type has
|
2022-01-18 19:13:13 -04:00
|
|
|
return sorted(set(dir(cls._member_type_)) | interesting)
|
2013-08-12 10:51:41 -03:00
|
|
|
|
2013-06-14 20:55:46 -03:00
|
|
|
def __getitem__(cls, name):
|
2022-01-17 11:18:13 -04:00
|
|
|
"""
|
|
|
|
Return the member matching `name`.
|
|
|
|
"""
|
2013-07-19 23:47:21 -03:00
|
|
|
return cls._member_map_[name]
|
2013-06-14 20:55:46 -03:00
|
|
|
|
|
|
|
def __iter__(cls):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
2022-01-17 11:18:13 -04:00
|
|
|
Return members in definition order.
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
2013-07-19 23:47:21 -03:00
|
|
|
return (cls._member_map_[name] for name in cls._member_names_)
|
2013-06-14 20:55:46 -03:00
|
|
|
|
|
|
|
def __len__(cls):
|
2022-01-17 11:18:13 -04:00
|
|
|
"""
|
|
|
|
Return the number of members (no aliases)
|
|
|
|
"""
|
2013-07-19 23:47:21 -03:00
|
|
|
return len(cls._member_names_)
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
@bltns.property
|
2013-09-14 22:11:24 -03:00
|
|
|
def __members__(cls):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Returns a mapping of member name->value.
|
2013-09-14 22:11:24 -03:00
|
|
|
|
|
|
|
This mapping lists all enum members, including aliases. Note that this
|
|
|
|
is a read-only view of the internal mapping.
|
|
|
|
"""
|
|
|
|
return MappingProxyType(cls._member_map_)
|
|
|
|
|
2013-06-14 20:55:46 -03:00
|
|
|
def __repr__(cls):
|
2021-06-09 13:03:55 -03:00
|
|
|
if Flag is not None and issubclass(cls, Flag):
|
|
|
|
return "<flag %r>" % cls.__name__
|
|
|
|
else:
|
|
|
|
return "<enum %r>" % cls.__name__
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2013-09-14 22:11:24 -03:00
|
|
|
def __reversed__(cls):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
2022-01-17 11:18:13 -04:00
|
|
|
Return members in reverse definition order.
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
2013-09-14 22:11:24 -03:00
|
|
|
return (cls._member_map_[name] for name in reversed(cls._member_names_))
|
|
|
|
|
2013-09-06 11:16:48 -03:00
|
|
|
def __setattr__(cls, name, value):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Block attempts to reassign Enum members.
|
2013-09-06 11:16:48 -03:00
|
|
|
|
|
|
|
A simple assignment to the class namespace only changes one of the
|
|
|
|
several possible ways to get an Enum member from the Enum class,
|
|
|
|
resulting in an inconsistent Enumeration.
|
|
|
|
"""
|
|
|
|
member_map = cls.__dict__.get('_member_map_', {})
|
|
|
|
if name in member_map:
|
2022-01-17 11:18:13 -04:00
|
|
|
raise AttributeError('cannot reassign member %r' % (name, ))
|
2013-09-06 11:16:48 -03:00
|
|
|
super().__setattr__(name, value)
|
|
|
|
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
def _create_(cls, class_name, names, *, module=None, qualname=None, type=None, start=1, boundary=None):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Convenience method to create a new Enum class.
|
2013-06-14 20:55:46 -03:00
|
|
|
|
|
|
|
`names` can be:
|
|
|
|
|
|
|
|
* A string containing member names, separated either with spaces or
|
2014-09-17 00:35:55 -03:00
|
|
|
commas. Values are incremented by 1 from `start`.
|
|
|
|
* An iterable of member names. Values are incremented by 1 from `start`.
|
2013-06-14 20:55:46 -03:00
|
|
|
* An iterable of (member name, value) pairs.
|
2014-09-17 00:35:55 -03:00
|
|
|
* A mapping of member name -> value pairs.
|
2013-06-14 20:55:46 -03:00
|
|
|
"""
|
|
|
|
metacls = cls.__class__
|
|
|
|
bases = (cls, ) if type is None else (type, cls)
|
2022-01-14 18:18:00 -04:00
|
|
|
_, first_enum = cls._get_mixins_(class_name, bases)
|
2013-06-14 20:55:46 -03:00
|
|
|
classdict = metacls.__prepare__(class_name, bases)
|
|
|
|
|
|
|
|
# special processing needed for names?
|
|
|
|
if isinstance(names, str):
|
|
|
|
names = names.replace(',', ' ').split()
|
2017-06-21 13:52:32 -03:00
|
|
|
if isinstance(names, (tuple, list)) and names and isinstance(names[0], str):
|
2016-08-31 04:12:15 -03:00
|
|
|
original_names, names = names, []
|
2016-09-11 03:36:59 -03:00
|
|
|
last_values = []
|
2016-08-31 04:12:15 -03:00
|
|
|
for count, name in enumerate(original_names):
|
2016-09-11 03:36:59 -03:00
|
|
|
value = first_enum._generate_next_value_(name, start, count, last_values[:])
|
|
|
|
last_values.append(value)
|
|
|
|
names.append((name, value))
|
2023-08-31 16:45:12 -03:00
|
|
|
if names is None:
|
|
|
|
names = ()
|
2013-06-14 20:55:46 -03:00
|
|
|
|
|
|
|
# Here, names is either an iterable of (name, value) or a mapping.
|
|
|
|
for item in names:
|
|
|
|
if isinstance(item, str):
|
|
|
|
member_name, member_value = item, names[item]
|
|
|
|
else:
|
|
|
|
member_name, member_value = item
|
|
|
|
classdict[member_name] = member_value
|
|
|
|
|
|
|
|
if module is None:
|
|
|
|
try:
|
2023-01-13 07:31:06 -04:00
|
|
|
module = sys._getframemodulename(2)
|
|
|
|
except AttributeError:
|
|
|
|
# Fall back on _getframe if _getframemodulename is missing
|
|
|
|
try:
|
|
|
|
module = sys._getframe(2).f_globals['__name__']
|
|
|
|
except (AttributeError, ValueError, KeyError):
|
|
|
|
pass
|
2013-06-14 20:55:46 -03:00
|
|
|
if module is None:
|
2021-01-13 03:47:57 -04:00
|
|
|
_make_class_unpicklable(classdict)
|
2013-06-14 20:55:46 -03:00
|
|
|
else:
|
2021-01-13 03:47:57 -04:00
|
|
|
classdict['__module__'] = module
|
2014-02-08 15:36:27 -04:00
|
|
|
if qualname is not None:
|
2021-01-13 03:47:57 -04:00
|
|
|
classdict['__qualname__'] = qualname
|
2013-06-14 20:55:46 -03:00
|
|
|
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
return metacls.__new__(metacls, class_name, bases, classdict, boundary=boundary)
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
def _convert_(cls, name, module, filter, source=None, *, boundary=None, as_global=False):
|
2018-09-12 14:28:53 -03:00
|
|
|
"""
|
|
|
|
Create a new Enum subclass that replaces a collection of global constants
|
|
|
|
"""
|
|
|
|
# convert all constants from source (or module) that pass filter() to
|
|
|
|
# a new Enum called name, and export the enum and its members back to
|
|
|
|
# module;
|
|
|
|
# also, replace the __reduce_ex__ method so unpickling works in
|
|
|
|
# previous Python versions
|
2021-03-31 01:17:26 -03:00
|
|
|
module_globals = sys.modules[module].__dict__
|
2018-09-12 14:28:53 -03:00
|
|
|
if source:
|
2021-03-31 01:17:26 -03:00
|
|
|
source = source.__dict__
|
2018-09-12 14:28:53 -03:00
|
|
|
else:
|
|
|
|
source = module_globals
|
|
|
|
# _value2member_map_ is populated in the same order every time
|
|
|
|
# for a consistent reverse mapping of number to name when there
|
|
|
|
# are multiple names for the same number.
|
|
|
|
members = [
|
|
|
|
(name, value)
|
|
|
|
for name, value in source.items()
|
|
|
|
if filter(name)]
|
|
|
|
try:
|
|
|
|
# sort by value
|
|
|
|
members.sort(key=lambda t: (t[1], t[0]))
|
|
|
|
except TypeError:
|
|
|
|
# unless some values aren't comparable, in which case sort by name
|
|
|
|
members.sort(key=lambda t: t[0])
|
2021-04-21 14:20:44 -03:00
|
|
|
body = {t[0]: t[1] for t in members}
|
|
|
|
body['__module__'] = module
|
|
|
|
tmp_cls = type(name, (object, ), body)
|
|
|
|
cls = _simple_enum(etype=cls, boundary=boundary or KEEP)(tmp_cls)
|
2022-01-17 11:18:13 -04:00
|
|
|
if as_global:
|
|
|
|
global_enum(cls)
|
|
|
|
else:
|
|
|
|
sys.modules[cls.__module__].__dict__.update(cls.__members__)
|
2018-09-12 14:28:53 -03:00
|
|
|
module_globals[name] = cls
|
|
|
|
return cls
|
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
@classmethod
|
|
|
|
def _check_for_existing_members_(mcls, class_name, bases):
|
2020-09-16 11:11:57 -03:00
|
|
|
for chain in bases:
|
|
|
|
for base in chain.__mro__:
|
2023-03-27 20:26:16 -03:00
|
|
|
if isinstance(base, EnumType) and base._member_names_:
|
2020-12-08 16:26:56 -04:00
|
|
|
raise TypeError(
|
2022-01-17 11:18:13 -04:00
|
|
|
"<enum %r> cannot extend %r"
|
|
|
|
% (class_name, base)
|
2020-12-08 16:26:56 -04:00
|
|
|
)
|
2020-09-16 11:11:57 -03:00
|
|
|
|
2022-01-14 18:18:00 -04:00
|
|
|
@classmethod
|
2022-01-17 11:18:13 -04:00
|
|
|
def _get_mixins_(mcls, class_name, bases):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Returns the type for creating enum members, and the first inherited
|
2013-06-14 20:55:46 -03:00
|
|
|
enum class.
|
|
|
|
|
|
|
|
bases: the tuple of bases that was given to __new__
|
|
|
|
"""
|
|
|
|
if not bases:
|
|
|
|
return object, Enum
|
2018-09-21 23:03:09 -03:00
|
|
|
# ensure final parent class is an Enum derivative, find any concrete
|
|
|
|
# data type, and check that Enum has no members
|
|
|
|
first_enum = bases[-1]
|
2023-03-27 20:26:16 -03:00
|
|
|
if not isinstance(first_enum, EnumType):
|
2018-09-21 23:03:09 -03:00
|
|
|
raise TypeError("new enumerations should be created as "
|
|
|
|
"`EnumName([mixin_type, ...] [data_type,] enum_type)`")
|
2022-01-17 11:18:13 -04:00
|
|
|
member_type = mcls._find_data_type_(class_name, bases) or object
|
2013-06-14 20:55:46 -03:00
|
|
|
return member_type, first_enum
|
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
@classmethod
|
|
|
|
def _find_data_repr_(mcls, class_name, bases):
|
|
|
|
for chain in bases:
|
|
|
|
for base in chain.__mro__:
|
|
|
|
if base is object:
|
|
|
|
continue
|
2023-03-27 20:26:16 -03:00
|
|
|
elif isinstance(base, EnumType):
|
2022-01-17 11:18:13 -04:00
|
|
|
# if we hit an Enum, use it's _value_repr_
|
|
|
|
return base._value_repr_
|
|
|
|
elif '__repr__' in base.__dict__:
|
|
|
|
# this is our data repr
|
2022-12-06 17:43:41 -04:00
|
|
|
# double-check if a dataclass with a default __repr__
|
|
|
|
if (
|
|
|
|
'__dataclass_fields__' in base.__dict__
|
|
|
|
and '__dataclass_params__' in base.__dict__
|
|
|
|
and base.__dict__['__dataclass_params__'].repr
|
|
|
|
):
|
|
|
|
return _dataclass_repr
|
|
|
|
else:
|
|
|
|
return base.__dict__['__repr__']
|
2022-01-17 11:18:13 -04:00
|
|
|
return None
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _find_data_type_(mcls, class_name, bases):
|
2023-04-13 12:31:03 -03:00
|
|
|
# a datatype has a __new__ method, or a __dataclass_fields__ attribute
|
2022-01-17 11:18:13 -04:00
|
|
|
data_types = set()
|
2022-07-17 22:51:04 -03:00
|
|
|
base_chain = set()
|
2022-01-17 11:18:13 -04:00
|
|
|
for chain in bases:
|
|
|
|
candidate = None
|
|
|
|
for base in chain.__mro__:
|
2022-07-17 22:51:04 -03:00
|
|
|
base_chain.add(base)
|
2022-01-17 11:18:13 -04:00
|
|
|
if base is object:
|
|
|
|
continue
|
2023-03-27 20:26:16 -03:00
|
|
|
elif isinstance(base, EnumType):
|
2022-01-17 11:18:13 -04:00
|
|
|
if base._member_type_ is not object:
|
|
|
|
data_types.add(base._member_type_)
|
|
|
|
break
|
2023-04-13 12:31:03 -03:00
|
|
|
elif '__new__' in base.__dict__ or '__dataclass_fields__' in base.__dict__:
|
2022-01-17 11:18:13 -04:00
|
|
|
data_types.add(candidate or base)
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
candidate = candidate or base
|
|
|
|
if len(data_types) > 1:
|
|
|
|
raise TypeError('too many data types for %r: %r' % (class_name, data_types))
|
|
|
|
elif data_types:
|
|
|
|
return data_types.pop()
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _find_new_(mcls, classdict, member_type, first_enum):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Returns the __new__ to be used for creating the enum members.
|
2013-06-14 20:55:46 -03:00
|
|
|
|
|
|
|
classdict: the class dictionary given to __new__
|
|
|
|
member_type: the data type whose __new__ will be used by default
|
|
|
|
first_enum: enumeration to check for an overriding __new__
|
|
|
|
"""
|
|
|
|
# now find the correct __new__, checking to see of one was defined
|
|
|
|
# by the user; also check earlier enum classes in case a __new__ was
|
|
|
|
# saved as __new_member__
|
|
|
|
__new__ = classdict.get('__new__', None)
|
|
|
|
|
|
|
|
# should __new__ be saved as __new_member__ later?
|
2021-04-21 14:20:44 -03:00
|
|
|
save_new = first_enum is not None and __new__ is not None
|
2013-06-14 20:55:46 -03:00
|
|
|
|
|
|
|
if __new__ is None:
|
|
|
|
# check all possibles for __new_member__ before falling back to
|
|
|
|
# __new__
|
|
|
|
for method in ('__new_member__', '__new__'):
|
|
|
|
for possible in (member_type, first_enum):
|
|
|
|
target = getattr(possible, method, None)
|
|
|
|
if target not in {
|
|
|
|
None,
|
|
|
|
None.__new__,
|
|
|
|
object.__new__,
|
|
|
|
Enum.__new__,
|
|
|
|
}:
|
|
|
|
__new__ = target
|
|
|
|
break
|
|
|
|
if __new__ is not None:
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
__new__ = object.__new__
|
|
|
|
|
|
|
|
# if a non-object.__new__ is used then whatever value/tuple was
|
|
|
|
# assigned to the enum member name will be passed to __new__ and to the
|
|
|
|
# new enum member's __init__
|
2021-04-21 14:20:44 -03:00
|
|
|
if first_enum is None or __new__ in (Enum.__new__, object.__new__):
|
2013-06-14 20:55:46 -03:00
|
|
|
use_args = False
|
|
|
|
else:
|
|
|
|
use_args = True
|
|
|
|
return __new__, save_new, use_args
|
2023-12-05 12:27:36 -04:00
|
|
|
|
|
|
|
def _add_member_(cls, name, member):
|
|
|
|
# _value_ structures are not updated
|
|
|
|
if name in cls._member_map_:
|
|
|
|
if cls._member_map_[name] is not member:
|
|
|
|
raise NameError('%r is already bound: %r' % (name, cls._member_map_[name]))
|
|
|
|
return
|
|
|
|
#
|
|
|
|
# if necessary, get redirect in place and then add it to _member_map_
|
|
|
|
found_descriptor = None
|
|
|
|
descriptor_type = None
|
|
|
|
class_type = None
|
|
|
|
for base in cls.__mro__[1:]:
|
|
|
|
attr = base.__dict__.get(name)
|
|
|
|
if attr is not None:
|
|
|
|
if isinstance(attr, (property, DynamicClassAttribute)):
|
|
|
|
found_descriptor = attr
|
|
|
|
class_type = base
|
|
|
|
descriptor_type = 'enum'
|
|
|
|
break
|
|
|
|
elif _is_descriptor(attr):
|
|
|
|
found_descriptor = attr
|
|
|
|
descriptor_type = descriptor_type or 'desc'
|
|
|
|
class_type = class_type or base
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
descriptor_type = 'attr'
|
|
|
|
class_type = base
|
|
|
|
if found_descriptor:
|
|
|
|
redirect = property()
|
|
|
|
redirect.member = member
|
|
|
|
redirect.__set_name__(cls, name)
|
|
|
|
if descriptor_type in ('enum', 'desc'):
|
|
|
|
# earlier descriptor found; copy fget, fset, fdel to this one.
|
|
|
|
redirect.fget = getattr(found_descriptor, 'fget', None)
|
|
|
|
redirect._get = getattr(found_descriptor, '__get__', None)
|
|
|
|
redirect.fset = getattr(found_descriptor, 'fset', None)
|
|
|
|
redirect._set = getattr(found_descriptor, '__set__', None)
|
|
|
|
redirect.fdel = getattr(found_descriptor, 'fdel', None)
|
|
|
|
redirect._del = getattr(found_descriptor, '__delete__', None)
|
|
|
|
redirect._attr_type = descriptor_type
|
|
|
|
redirect._cls_type = class_type
|
|
|
|
setattr(cls, name, redirect)
|
|
|
|
else:
|
|
|
|
setattr(cls, name, member)
|
|
|
|
# now add to _member_map_ (even aliases)
|
|
|
|
cls._member_map_[name] = member
|
|
|
|
|
|
|
|
EnumMeta = EnumType # keep EnumMeta name for backwards compatibility
|
2013-06-14 20:55:46 -03:00
|
|
|
|
|
|
|
|
2021-03-31 01:17:26 -03:00
|
|
|
class Enum(metaclass=EnumType):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
2022-01-17 11:18:13 -04:00
|
|
|
Create a collection of name/value pairs.
|
|
|
|
|
|
|
|
Example enumeration:
|
|
|
|
|
|
|
|
>>> class Color(Enum):
|
|
|
|
... RED = 1
|
|
|
|
... BLUE = 2
|
|
|
|
... GREEN = 3
|
|
|
|
|
|
|
|
Access them by:
|
|
|
|
|
2022-12-07 22:24:52 -04:00
|
|
|
- attribute access:
|
2022-01-17 11:18:13 -04:00
|
|
|
|
2022-12-07 22:24:52 -04:00
|
|
|
>>> Color.RED
|
|
|
|
<Color.RED: 1>
|
2022-01-17 11:18:13 -04:00
|
|
|
|
|
|
|
- value lookup:
|
|
|
|
|
2022-12-07 22:24:52 -04:00
|
|
|
>>> Color(1)
|
|
|
|
<Color.RED: 1>
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
- name lookup:
|
|
|
|
|
2022-12-07 22:24:52 -04:00
|
|
|
>>> Color['RED']
|
|
|
|
<Color.RED: 1>
|
2022-01-17 11:18:13 -04:00
|
|
|
|
|
|
|
Enumerations can be iterated over, and know how many members they have:
|
|
|
|
|
|
|
|
>>> len(Color)
|
|
|
|
3
|
|
|
|
|
|
|
|
>>> list(Color)
|
|
|
|
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
|
|
|
|
|
|
|
|
Methods can be added to enumerations, and members can have their own
|
|
|
|
attributes -- see the documentation for details.
|
2013-06-14 20:55:46 -03:00
|
|
|
"""
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
|
2022-12-16 16:30:47 -04:00
|
|
|
@classmethod
|
|
|
|
def __signature__(cls):
|
|
|
|
if cls._member_names_:
|
|
|
|
return '(*values)'
|
|
|
|
else:
|
|
|
|
return '(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)'
|
|
|
|
|
2013-06-14 20:55:46 -03:00
|
|
|
def __new__(cls, value):
|
|
|
|
# all enum instances are actually created during class construction
|
|
|
|
# without calling this method; this method is called by the metaclass'
|
|
|
|
# __call__ (i.e. Color(3) ), and by pickle
|
|
|
|
if type(value) is cls:
|
2016-11-21 13:22:05 -04:00
|
|
|
# For lookups like Color(Color.RED)
|
2013-06-14 20:55:46 -03:00
|
|
|
return value
|
|
|
|
# by-value search for a matching enum member
|
|
|
|
# see if it's in the reverse mapping (for hashable values)
|
2013-07-19 23:35:56 -03:00
|
|
|
try:
|
2018-12-26 14:45:33 -04:00
|
|
|
return cls._value2member_map_[value]
|
|
|
|
except KeyError:
|
|
|
|
# Not found, no need to do long O(n) search
|
|
|
|
pass
|
2013-07-19 23:35:56 -03:00
|
|
|
except TypeError:
|
|
|
|
# not there, now do long search -- O(n) behavior
|
2023-12-05 12:27:36 -04:00
|
|
|
for name, values in cls._unhashable_values_map_.items():
|
|
|
|
if value in values:
|
|
|
|
return cls[name]
|
2023-08-31 16:45:12 -03:00
|
|
|
# still not found -- verify that members exist, in-case somebody got here mistakenly
|
|
|
|
# (such as via super when trying to override __new__)
|
|
|
|
if not cls._member_map_:
|
2024-02-28 19:17:49 -04:00
|
|
|
if getattr(cls, '_%s__in_progress' % cls.__name__, False):
|
|
|
|
raise TypeError('do not use `super().__new__; call the appropriate __new__ directly') from None
|
2023-08-31 16:45:12 -03:00
|
|
|
raise TypeError("%r has no members defined" % cls)
|
|
|
|
#
|
2016-08-31 04:12:15 -03:00
|
|
|
# still not found -- try _missing_ hook
|
2018-09-12 15:43:34 -03:00
|
|
|
try:
|
|
|
|
exc = None
|
|
|
|
result = cls._missing_(value)
|
|
|
|
except Exception as e:
|
|
|
|
exc = e
|
|
|
|
result = None
|
2021-04-12 12:51:20 -03:00
|
|
|
try:
|
|
|
|
if isinstance(result, cls):
|
|
|
|
return result
|
|
|
|
elif (
|
|
|
|
Flag is not None and issubclass(cls, Flag)
|
|
|
|
and cls._boundary_ is EJECT and isinstance(result, int)
|
|
|
|
):
|
|
|
|
return result
|
|
|
|
else:
|
|
|
|
ve_exc = ValueError("%r is not a valid %s" % (value, cls.__qualname__))
|
|
|
|
if result is None and exc is None:
|
|
|
|
raise ve_exc
|
|
|
|
elif exc is None:
|
|
|
|
exc = TypeError(
|
|
|
|
'error in %s._missing_: returned %r instead of None or a valid member'
|
|
|
|
% (cls.__name__, result)
|
|
|
|
)
|
|
|
|
if not isinstance(exc, ValueError):
|
|
|
|
exc.__context__ = ve_exc
|
|
|
|
raise exc
|
|
|
|
finally:
|
|
|
|
# ensure all variables that could hold an exception are destroyed
|
|
|
|
exc = None
|
|
|
|
ve_exc = None
|
2016-08-31 04:12:15 -03:00
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
def __init__(self, *args, **kwds):
|
|
|
|
pass
|
|
|
|
|
2023-12-05 12:27:36 -04:00
|
|
|
def _add_alias_(self, name):
|
|
|
|
self.__class__._add_member_(name, self)
|
|
|
|
|
|
|
|
def _add_value_alias_(self, value):
|
|
|
|
cls = self.__class__
|
|
|
|
try:
|
|
|
|
if value in cls._value2member_map_:
|
|
|
|
if cls._value2member_map_[value] is not self:
|
|
|
|
raise ValueError('%r is already bound: %r' % (value, cls._value2member_map_[value]))
|
|
|
|
return
|
|
|
|
except TypeError:
|
|
|
|
# unhashable value, do long search
|
|
|
|
for m in cls._member_map_.values():
|
|
|
|
if m._value_ == value:
|
|
|
|
if m is not self:
|
|
|
|
raise ValueError('%r is already bound: %r' % (value, cls._value2member_map_[value]))
|
|
|
|
return
|
|
|
|
try:
|
|
|
|
# This may fail if value is not hashable. We can't add the value
|
|
|
|
# to the map, and by-value lookups for this value will be
|
|
|
|
# linear.
|
|
|
|
cls._value2member_map_.setdefault(value, self)
|
|
|
|
except TypeError:
|
|
|
|
# keep track of the value in a list so containment checks are quick
|
|
|
|
cls._unhashable_values_.append(value)
|
|
|
|
cls._unhashable_values_map_.setdefault(self.name, []).append(value)
|
|
|
|
|
2023-04-03 21:47:40 -03:00
|
|
|
@staticmethod
|
2022-06-23 11:48:25 -03:00
|
|
|
def _generate_next_value_(name, start, count, last_values):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Generate the next value when not given.
|
|
|
|
|
|
|
|
name: the name of the member
|
|
|
|
start: the initial start value or None
|
|
|
|
count: the number of existing members
|
2022-06-23 11:48:25 -03:00
|
|
|
last_values: the list of values assigned
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
2022-06-23 11:48:25 -03:00
|
|
|
if not last_values:
|
2022-06-23 03:20:24 -03:00
|
|
|
return start
|
|
|
|
try:
|
2023-05-22 22:59:40 -03:00
|
|
|
last_value = sorted(last_values).pop()
|
2022-06-23 03:20:24 -03:00
|
|
|
except TypeError:
|
2023-05-22 22:59:40 -03:00
|
|
|
raise TypeError('unable to sort non-numeric values') from None
|
|
|
|
try:
|
|
|
|
return last_value + 1
|
|
|
|
except TypeError:
|
|
|
|
raise TypeError('unable to increment %r' % (last_value, )) from None
|
2016-09-11 03:36:59 -03:00
|
|
|
|
2016-08-31 04:12:15 -03:00
|
|
|
@classmethod
|
|
|
|
def _missing_(cls, value):
|
2020-09-16 14:26:50 -03:00
|
|
|
return None
|
2013-06-14 20:55:46 -03:00
|
|
|
|
|
|
|
def __repr__(self):
|
2022-06-16 16:16:12 -03:00
|
|
|
v_repr = self.__class__._value_repr_ or repr
|
2022-01-17 11:18:13 -04:00
|
|
|
return "<%s.%s: %s>" % (self.__class__.__name__, self._name_, v_repr(self._value_))
|
2013-06-14 20:55:46 -03:00
|
|
|
|
|
|
|
def __str__(self):
|
2022-01-17 11:18:13 -04:00
|
|
|
return "%s.%s" % (self.__class__.__name__, self._name_, )
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2013-08-12 10:51:41 -03:00
|
|
|
def __dir__(self):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
2023-10-30 16:56:29 -03:00
|
|
|
Returns public methods and other interesting attributes.
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
2023-10-30 16:56:29 -03:00
|
|
|
interesting = set()
|
|
|
|
if self.__class__._member_type_ is not object:
|
2022-01-17 11:18:13 -04:00
|
|
|
interesting = set(object.__dir__(self))
|
|
|
|
for name in getattr(self, '__dict__', []):
|
2023-10-30 16:56:29 -03:00
|
|
|
if name[0] != '_' and name not in self._member_map_:
|
2022-01-17 11:18:13 -04:00
|
|
|
interesting.add(name)
|
|
|
|
for cls in self.__class__.mro():
|
|
|
|
for name, obj in cls.__dict__.items():
|
|
|
|
if name[0] == '_':
|
|
|
|
continue
|
|
|
|
if isinstance(obj, property):
|
|
|
|
# that's an enum.property
|
|
|
|
if obj.fget is not None or name not in self._member_map_:
|
|
|
|
interesting.add(name)
|
|
|
|
else:
|
|
|
|
# in case it was added by `dir(self)`
|
|
|
|
interesting.discard(name)
|
2023-10-30 16:56:29 -03:00
|
|
|
elif name not in self._member_map_:
|
2022-01-17 11:18:13 -04:00
|
|
|
interesting.add(name)
|
|
|
|
names = sorted(
|
|
|
|
set(['__class__', '__doc__', '__eq__', '__hash__', '__module__'])
|
|
|
|
| interesting
|
|
|
|
)
|
|
|
|
return names
|
2013-08-12 10:51:41 -03:00
|
|
|
|
2013-08-31 23:17:41 -03:00
|
|
|
def __format__(self, format_spec):
|
2022-01-17 11:18:13 -04:00
|
|
|
return str.__format__(str(self), format_spec)
|
2013-08-31 23:17:41 -03:00
|
|
|
|
2013-06-14 20:55:46 -03:00
|
|
|
def __hash__(self):
|
2013-07-19 23:47:21 -03:00
|
|
|
return hash(self._name_)
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2014-02-08 15:36:27 -04:00
|
|
|
def __reduce_ex__(self, proto):
|
2023-06-08 15:40:15 -03:00
|
|
|
return self.__class__, (self._value_, )
|
2014-02-08 15:36:27 -04:00
|
|
|
|
2023-07-12 18:01:17 -03:00
|
|
|
def __deepcopy__(self,memo):
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __copy__(self):
|
|
|
|
return self
|
|
|
|
|
2021-01-13 03:47:57 -04:00
|
|
|
# enum.property is used to provide access to the `name` and
|
|
|
|
# `value` attributes of enum members while keeping some measure of
|
2013-06-14 20:55:46 -03:00
|
|
|
# protection from modification, while still allowing for an enumeration
|
2022-07-25 15:05:10 -03:00
|
|
|
# to have members named `name` and `value`. This works because each
|
|
|
|
# instance of enum.property saves its companion member, which it returns
|
|
|
|
# on class lookup; on instance lookup it either executes a provided function
|
|
|
|
# or raises an AttributeError.
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2021-01-13 03:47:57 -04:00
|
|
|
@property
|
2013-06-14 20:55:46 -03:00
|
|
|
def name(self):
|
2013-09-15 20:59:35 -03:00
|
|
|
"""The name of the Enum member."""
|
2013-07-19 23:47:21 -03:00
|
|
|
return self._name_
|
2013-06-14 20:55:46 -03:00
|
|
|
|
2021-01-13 03:47:57 -04:00
|
|
|
@property
|
2013-06-14 20:55:46 -03:00
|
|
|
def value(self):
|
2013-09-15 20:59:35 -03:00
|
|
|
"""The value of the Enum member."""
|
2013-07-19 23:47:21 -03:00
|
|
|
return self._value_
|
2013-06-14 20:55:46 -03:00
|
|
|
|
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
class ReprEnum(Enum):
|
2020-09-21 21:23:13 -03:00
|
|
|
"""
|
2022-01-17 11:18:13 -04:00
|
|
|
Only changes the repr(), leaving str() and format() to the mixed-in type.
|
2020-09-21 21:23:13 -03:00
|
|
|
"""
|
|
|
|
|
2021-06-18 17:15:46 -03:00
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
class IntEnum(int, ReprEnum):
|
|
|
|
"""
|
|
|
|
Enum where members are also (and must be) ints
|
|
|
|
"""
|
2021-06-18 17:15:46 -03:00
|
|
|
|
2020-09-21 21:23:13 -03:00
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
class StrEnum(str, ReprEnum):
|
2020-09-21 21:23:13 -03:00
|
|
|
"""
|
|
|
|
Enum where members are also (and must be) strings
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __new__(cls, *values):
|
2022-01-17 11:18:13 -04:00
|
|
|
"values must already be of type `str`"
|
2020-09-21 21:23:13 -03:00
|
|
|
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], ))
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
if len(values) >= 2:
|
2020-09-21 21:23:13 -03:00
|
|
|
# check that encoding argument is a string
|
|
|
|
if not isinstance(values[1], str):
|
|
|
|
raise TypeError('encoding must be a string, not %r' % (values[1], ))
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
if len(values) == 3:
|
|
|
|
# check that errors argument is a string
|
|
|
|
if not isinstance(values[2], str):
|
|
|
|
raise TypeError('errors must be a string, not %r' % (values[2]))
|
2020-09-21 21:23:13 -03:00
|
|
|
value = str(*values)
|
|
|
|
member = str.__new__(cls, value)
|
|
|
|
member._value_ = value
|
|
|
|
return member
|
2013-07-18 21:05:39 -03:00
|
|
|
|
2023-04-03 21:47:40 -03:00
|
|
|
@staticmethod
|
2020-12-10 16:20:06 -04:00
|
|
|
def _generate_next_value_(name, start, count, last_values):
|
|
|
|
"""
|
|
|
|
Return the lower-cased version of the member name.
|
|
|
|
"""
|
|
|
|
return name.lower()
|
|
|
|
|
2013-07-18 21:05:39 -03:00
|
|
|
|
2023-06-08 15:40:15 -03:00
|
|
|
def pickle_by_global_name(self, proto):
|
|
|
|
# should not be used with Flag-type enums
|
2015-03-18 21:27:57 -03:00
|
|
|
return self.name
|
2023-06-08 15:40:15 -03:00
|
|
|
_reduce_ex_by_global_name = pickle_by_global_name
|
|
|
|
|
|
|
|
def pickle_by_enum_name(self, proto):
|
|
|
|
# should not be used with Flag-type enums
|
|
|
|
return getattr, (self.__class__, self._name_)
|
2015-03-18 21:27:57 -03:00
|
|
|
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
class FlagBoundary(StrEnum):
|
|
|
|
"""
|
|
|
|
control how out of range values are handled
|
2023-04-13 12:24:33 -03:00
|
|
|
"strict" -> error is raised [default for Flag]
|
|
|
|
"conform" -> extra bits are discarded
|
2023-04-03 18:57:42 -03:00
|
|
|
"eject" -> lose flag status
|
|
|
|
"keep" -> keep flag status and all bits [default for IntFlag]
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
"""
|
|
|
|
STRICT = auto()
|
|
|
|
CONFORM = auto()
|
|
|
|
EJECT = auto()
|
|
|
|
KEEP = auto()
|
|
|
|
STRICT, CONFORM, EJECT, KEEP = FlagBoundary
|
|
|
|
|
|
|
|
|
2023-04-13 12:24:33 -03:00
|
|
|
class Flag(Enum, boundary=STRICT):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Support for flags
|
|
|
|
"""
|
2016-09-11 03:36:59 -03:00
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
_numeric_repr_ = repr
|
|
|
|
|
2023-04-03 21:47:40 -03:00
|
|
|
@staticmethod
|
2016-09-11 03:36:59 -03:00
|
|
|
def _generate_next_value_(name, start, count, last_values):
|
2016-08-31 04:12:15 -03:00
|
|
|
"""
|
|
|
|
Generate the next value when not given.
|
|
|
|
|
|
|
|
name: the name of the member
|
2019-09-21 02:22:54 -03:00
|
|
|
start: the initial start value or None
|
2016-08-31 04:12:15 -03:00
|
|
|
count: the number of existing members
|
2022-06-23 11:48:25 -03:00
|
|
|
last_values: the last value assigned or None
|
2016-08-31 04:12:15 -03:00
|
|
|
"""
|
|
|
|
if not count:
|
|
|
|
return start if start is not None else 1
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
last_value = max(last_values)
|
|
|
|
try:
|
|
|
|
high_bit = _high_bit(last_value)
|
|
|
|
except Exception:
|
2022-01-17 11:18:13 -04:00
|
|
|
raise TypeError('invalid flag value %r' % last_value) from None
|
2016-08-31 04:12:15 -03:00
|
|
|
return 2 ** (high_bit+1)
|
|
|
|
|
|
|
|
@classmethod
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
def _iter_member_by_value_(cls, value):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
Extract all members from the value in definition (i.e. increasing value) order.
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
for val in _iter_bits_lsb(value & cls._flag_mask_):
|
|
|
|
yield cls._value2member_map_.get(val)
|
|
|
|
|
|
|
|
_iter_member_ = _iter_member_by_value_
|
2016-08-31 04:12:15 -03:00
|
|
|
|
|
|
|
@classmethod
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
def _iter_member_by_def_(cls, value):
|
|
|
|
"""
|
|
|
|
Extract all members from the value in definition order.
|
|
|
|
"""
|
|
|
|
yield from sorted(
|
|
|
|
cls._iter_member_by_value_(value),
|
|
|
|
key=lambda m: m._sort_order_,
|
|
|
|
)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _missing_(cls, value):
|
2016-09-18 17:15:41 -03:00
|
|
|
"""
|
2021-04-15 10:49:54 -03:00
|
|
|
Create a composite member containing all canonical members present in `value`.
|
|
|
|
|
|
|
|
If non-member values are present, result depends on `_boundary_` setting.
|
2016-09-18 17:15:41 -03:00
|
|
|
"""
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
if not isinstance(value, int):
|
|
|
|
raise ValueError(
|
|
|
|
"%r is not a valid %s" % (value, cls.__qualname__)
|
|
|
|
)
|
|
|
|
# check boundaries
|
|
|
|
# - value must be in range (e.g. -16 <-> +15, i.e. ~15 <-> 15)
|
|
|
|
# - value must not include any skipped flags (e.g. if bit 2 is not
|
|
|
|
# defined, then 0d10 is invalid)
|
|
|
|
flag_mask = cls._flag_mask_
|
2023-04-13 12:24:33 -03:00
|
|
|
singles_mask = cls._singles_mask_
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
all_bits = cls._all_bits_
|
|
|
|
neg_value = None
|
|
|
|
if (
|
|
|
|
not ~all_bits <= value <= all_bits
|
|
|
|
or value & (all_bits ^ flag_mask)
|
|
|
|
):
|
|
|
|
if cls._boundary_ is STRICT:
|
|
|
|
max_bits = max(value.bit_length(), flag_mask.bit_length())
|
|
|
|
raise ValueError(
|
2022-01-17 11:18:13 -04:00
|
|
|
"%r invalid value %r\n given %s\n allowed %s" % (
|
|
|
|
cls, value, bin(value, max_bits), bin(flag_mask, max_bits),
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
))
|
|
|
|
elif cls._boundary_ is CONFORM:
|
|
|
|
value = value & flag_mask
|
|
|
|
elif cls._boundary_ is EJECT:
|
|
|
|
return value
|
|
|
|
elif cls._boundary_ is KEEP:
|
|
|
|
if value < 0:
|
|
|
|
value = (
|
|
|
|
max(all_bits+1, 2**(value.bit_length()))
|
|
|
|
+ value
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
raise ValueError(
|
2022-01-17 11:18:13 -04:00
|
|
|
'%r unknown flag boundary %r' % (cls, cls._boundary_, )
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
)
|
|
|
|
if value < 0:
|
|
|
|
neg_value = value
|
|
|
|
value = all_bits + 1 + value
|
|
|
|
# get members and unknown
|
|
|
|
unknown = value & ~flag_mask
|
2023-04-13 12:24:33 -03:00
|
|
|
aliases = value & ~singles_mask
|
|
|
|
member_value = value & singles_mask
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
if unknown and cls._boundary_ is not KEEP:
|
|
|
|
raise ValueError(
|
|
|
|
'%s(%r) --> unknown values %r [%s]'
|
|
|
|
% (cls.__name__, value, unknown, bin(unknown))
|
|
|
|
)
|
|
|
|
# normal Flag?
|
2023-02-05 23:29:06 -04:00
|
|
|
if cls._member_type_ is object:
|
2016-09-18 17:15:41 -03:00
|
|
|
# construct a singleton enum pseudo-member
|
2016-08-31 04:12:15 -03:00
|
|
|
pseudo_member = object.__new__(cls)
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
else:
|
2023-02-05 23:29:06 -04:00
|
|
|
pseudo_member = cls._member_type_.__new__(cls, value)
|
2021-04-21 14:20:44 -03:00
|
|
|
if not hasattr(pseudo_member, '_value_'):
|
2016-08-31 04:12:15 -03:00
|
|
|
pseudo_member._value_ = value
|
2023-04-13 12:24:33 -03:00
|
|
|
if member_value or aliases:
|
|
|
|
members = []
|
|
|
|
combined_value = 0
|
|
|
|
for m in cls._iter_member_(member_value):
|
|
|
|
members.append(m)
|
|
|
|
combined_value |= m._value_
|
|
|
|
if aliases:
|
|
|
|
value = member_value | aliases
|
|
|
|
for n, pm in cls._member_map_.items():
|
|
|
|
if pm not in members and pm._value_ and pm._value_ & value == pm._value_:
|
|
|
|
members.append(pm)
|
|
|
|
combined_value |= pm._value_
|
|
|
|
unknown = value ^ combined_value
|
|
|
|
pseudo_member._name_ = '|'.join([m._name_ for m in members])
|
|
|
|
if not combined_value:
|
|
|
|
pseudo_member._name_ = None
|
|
|
|
elif unknown and cls._boundary_ is STRICT:
|
|
|
|
raise ValueError('%r: no members with value %r' % (cls, unknown))
|
|
|
|
elif unknown:
|
2022-01-17 11:18:13 -04:00
|
|
|
pseudo_member._name_ += '|%s' % cls._numeric_repr_(unknown)
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
else:
|
|
|
|
pseudo_member._name_ = None
|
|
|
|
# use setdefault in case another thread already created a composite
|
2023-06-09 12:56:05 -03:00
|
|
|
# with this value
|
|
|
|
# note: zero is a special case -- always add it
|
|
|
|
pseudo_member = cls._value2member_map_.setdefault(value, pseudo_member)
|
|
|
|
if neg_value is not None:
|
|
|
|
cls._value2member_map_[neg_value] = pseudo_member
|
2016-08-31 04:12:15 -03:00
|
|
|
return pseudo_member
|
|
|
|
|
|
|
|
def __contains__(self, other):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Returns True if self has at least the same flags set as other.
|
|
|
|
"""
|
2016-08-31 04:12:15 -03:00
|
|
|
if not isinstance(other, self.__class__):
|
2018-09-10 15:21:04 -03:00
|
|
|
raise TypeError(
|
2022-01-17 11:18:13 -04:00
|
|
|
"unsupported operand type(s) for 'in': %r and %r" % (
|
2018-09-10 15:21:04 -03:00
|
|
|
type(other).__qualname__, self.__class__.__qualname__))
|
2016-08-31 04:12:15 -03:00
|
|
|
return other._value_ & self._value_ == other._value_
|
|
|
|
|
2020-09-16 17:01:00 -03:00
|
|
|
def __iter__(self):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
Returns flags in definition order.
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
yield from self._iter_member_(self._value_)
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return self._value_.bit_count()
|
2020-09-16 17:01:00 -03:00
|
|
|
|
2016-08-31 04:12:15 -03:00
|
|
|
def __repr__(self):
|
2021-03-31 01:17:26 -03:00
|
|
|
cls_name = self.__class__.__name__
|
2022-06-16 16:16:12 -03:00
|
|
|
v_repr = self.__class__._value_repr_ or repr
|
2021-03-31 01:17:26 -03:00
|
|
|
if self._name_ is None:
|
2022-01-17 11:18:13 -04:00
|
|
|
return "<%s: %s>" % (cls_name, v_repr(self._value_))
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
else:
|
2022-01-17 11:18:13 -04:00
|
|
|
return "<%s.%s: %s>" % (cls_name, self._name_, v_repr(self._value_))
|
2016-08-31 04:12:15 -03:00
|
|
|
|
|
|
|
def __str__(self):
|
2022-01-17 11:18:13 -04:00
|
|
|
cls_name = self.__class__.__name__
|
2021-03-31 01:17:26 -03:00
|
|
|
if self._name_ is None:
|
2022-01-17 11:18:13 -04:00
|
|
|
return '%s(%r)' % (cls_name, self._value_)
|
2016-08-31 04:12:15 -03:00
|
|
|
else:
|
2022-01-17 11:18:13 -04:00
|
|
|
return "%s.%s" % (cls_name, self._name_)
|
2016-08-31 04:12:15 -03:00
|
|
|
|
2016-09-02 20:32:32 -03:00
|
|
|
def __bool__(self):
|
|
|
|
return bool(self._value_)
|
|
|
|
|
2024-02-19 18:36:11 -04:00
|
|
|
def _get_value(self, flag):
|
|
|
|
if isinstance(flag, self.__class__):
|
|
|
|
return flag._value_
|
|
|
|
elif self._member_type_ is not object and isinstance(flag, self._member_type_):
|
|
|
|
return flag
|
|
|
|
return NotImplemented
|
|
|
|
|
2016-08-31 04:12:15 -03:00
|
|
|
def __or__(self, other):
|
2024-02-19 18:36:11 -04:00
|
|
|
other_value = self._get_value(other)
|
|
|
|
if other_value is NotImplemented:
|
2016-08-31 04:12:15 -03:00
|
|
|
return NotImplemented
|
2024-02-19 18:36:11 -04:00
|
|
|
|
|
|
|
for flag in self, other:
|
|
|
|
if self._get_value(flag) is None:
|
|
|
|
raise TypeError(f"'{flag}' cannot be combined with other flags with |")
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
value = self._value_
|
2024-02-19 18:36:11 -04:00
|
|
|
return self.__class__(value | other_value)
|
2016-08-31 04:12:15 -03:00
|
|
|
|
|
|
|
def __and__(self, other):
|
2024-02-19 18:36:11 -04:00
|
|
|
other_value = self._get_value(other)
|
|
|
|
if other_value is NotImplemented:
|
2016-08-31 04:12:15 -03:00
|
|
|
return NotImplemented
|
2024-02-19 18:36:11 -04:00
|
|
|
|
|
|
|
for flag in self, other:
|
|
|
|
if self._get_value(flag) is None:
|
|
|
|
raise TypeError(f"'{flag}' cannot be combined with other flags with &")
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
value = self._value_
|
2024-02-19 18:36:11 -04:00
|
|
|
return self.__class__(value & other_value)
|
2016-08-31 04:12:15 -03:00
|
|
|
|
|
|
|
def __xor__(self, other):
|
2024-02-19 18:36:11 -04:00
|
|
|
other_value = self._get_value(other)
|
|
|
|
if other_value is NotImplemented:
|
2016-08-31 04:12:15 -03:00
|
|
|
return NotImplemented
|
2024-02-19 18:36:11 -04:00
|
|
|
|
|
|
|
for flag in self, other:
|
|
|
|
if self._get_value(flag) is None:
|
|
|
|
raise TypeError(f"'{flag}' cannot be combined with other flags with ^")
|
bpo-38250: [Enum] single-bit flags are canonical (GH-24215)
Flag members are now divided by one-bit verses multi-bit, with multi-bit being treated as aliases. Iterating over a flag only returns the contained single-bit flags.
Iterating, repr(), and str() show members in definition order.
When constructing combined-member flags, any extra integer values are either discarded (CONFORM), turned into ints (EJECT) or treated as errors (STRICT). Flag classes can specify which of those three behaviors is desired:
>>> class Test(Flag, boundary=CONFORM):
... ONE = 1
... TWO = 2
...
>>> Test(5)
<Test.ONE: 1>
Besides the three above behaviors, there is also KEEP, which should not be used unless necessary -- for example, _convert_ specifies KEEP as there are flag sets in the stdlib that are incomplete and/or inconsistent (e.g. ssl.Options). KEEP will, as the name suggests, keep all bits; however, iterating over a flag with extra bits will only return the canonical flags contained, not the extra bits.
Iteration is now in member definition order. If member definition order
matches increasing value order, then a more efficient method of flag
decomposition is used; otherwise, sort() is called on the results of
that method to get definition order.
``re`` module:
repr() has been modified to support as closely as possible its previous
output; the big difference is that inverted flags cannot be output as
before because the inversion operation now always returns the comparable
positive result; i.e.
re.A|re.I|re.M|re.S is ~(re.L|re.U|re.S|re.T|re.DEBUG)
in both of the above terms, the ``value`` is 282.
re's tests have been updated to reflect the modifications to repr().
2021-01-25 18:26:19 -04:00
|
|
|
value = self._value_
|
2024-02-19 18:36:11 -04:00
|
|
|
return self.__class__(value ^ other_value)
|
2016-08-31 04:12:15 -03:00
|
|
|
|
2022-01-22 22:27:52 -04:00
|
|
|
def __invert__(self):
|
2024-02-19 18:36:11 -04:00
|
|
|
if self._get_value(self) is None:
|
|
|
|
raise TypeError(f"'{self}' cannot be inverted")
|
|
|
|
|
2022-01-22 22:27:52 -04:00
|
|
|
if self._inverted_ is None:
|
2023-07-11 08:35:54 -03:00
|
|
|
if self._boundary_ in (EJECT, KEEP):
|
2022-01-22 22:27:52 -04:00
|
|
|
self._inverted_ = self.__class__(~self._value_)
|
|
|
|
else:
|
2023-07-11 08:35:54 -03:00
|
|
|
self._inverted_ = self.__class__(self._singles_mask_ & ~self._value_)
|
2022-01-22 22:27:52 -04:00
|
|
|
return self._inverted_
|
|
|
|
|
2016-08-31 04:12:15 -03:00
|
|
|
__rand__ = __and__
|
2022-01-22 22:27:52 -04:00
|
|
|
__ror__ = __or__
|
2016-08-31 04:12:15 -03:00
|
|
|
__rxor__ = __xor__
|
2022-01-22 22:27:52 -04:00
|
|
|
|
|
|
|
|
2022-05-27 19:14:28 -03:00
|
|
|
class IntFlag(int, ReprEnum, Flag, boundary=KEEP):
|
2022-01-22 22:27:52 -04:00
|
|
|
"""
|
|
|
|
Support for integer-based Flags
|
|
|
|
"""
|
2016-08-31 04:12:15 -03:00
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
|
2016-08-31 04:12:15 -03:00
|
|
|
def _high_bit(value):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
returns index of highest bit, or -1 if value is zero or negative
|
|
|
|
"""
|
2016-09-18 17:15:41 -03:00
|
|
|
return value.bit_length() - 1
|
2016-08-31 04:12:15 -03:00
|
|
|
|
2013-07-18 21:05:39 -03:00
|
|
|
def unique(enumeration):
|
2020-12-08 16:26:56 -04:00
|
|
|
"""
|
|
|
|
Class decorator for enumerations ensuring unique member values.
|
|
|
|
"""
|
2013-07-18 21:05:39 -03:00
|
|
|
duplicates = []
|
|
|
|
for name, member in enumeration.__members__.items():
|
|
|
|
if name != member.name:
|
|
|
|
duplicates.append((name, member.name))
|
|
|
|
if duplicates:
|
|
|
|
alias_details = ', '.join(
|
|
|
|
["%s -> %s" % (alias, name) for (alias, name) in duplicates])
|
|
|
|
raise ValueError('duplicate values found in %r: %s' %
|
|
|
|
(enumeration, alias_details))
|
|
|
|
return enumeration
|
2016-09-18 17:15:41 -03:00
|
|
|
|
2022-12-06 17:43:41 -04:00
|
|
|
def _dataclass_repr(self):
|
|
|
|
dcf = self.__dataclass_fields__
|
|
|
|
return ', '.join(
|
|
|
|
'%s=%r' % (k, getattr(self, k))
|
|
|
|
for k in dcf.keys()
|
|
|
|
if dcf[k].repr
|
|
|
|
)
|
|
|
|
|
2021-03-31 01:17:26 -03:00
|
|
|
def global_enum_repr(self):
|
2021-08-25 11:24:32 -03:00
|
|
|
"""
|
|
|
|
use module.enum_name instead of class.enum_name
|
|
|
|
|
|
|
|
the module is the last module in case of a multi-module name
|
|
|
|
"""
|
|
|
|
module = self.__class__.__module__.split('.')[-1]
|
|
|
|
return '%s.%s' % (module, self._name_)
|
2021-03-31 01:17:26 -03:00
|
|
|
|
|
|
|
def global_flag_repr(self):
|
2021-08-25 11:24:32 -03:00
|
|
|
"""
|
|
|
|
use module.flag_name instead of class.flag_name
|
|
|
|
|
|
|
|
the module is the last module in case of a multi-module name
|
|
|
|
"""
|
|
|
|
module = self.__class__.__module__.split('.')[-1]
|
2021-03-31 01:17:26 -03:00
|
|
|
cls_name = self.__class__.__name__
|
|
|
|
if self._name_ is None:
|
2022-01-17 11:18:13 -04:00
|
|
|
return "%s.%s(%r)" % (module, cls_name, self._value_)
|
2024-03-11 19:41:53 -03:00
|
|
|
if _is_single_bit(self._value_):
|
2021-03-31 01:17:26 -03:00
|
|
|
return '%s.%s' % (module, self._name_)
|
|
|
|
if self._boundary_ is not FlagBoundary.KEEP:
|
2021-08-25 11:24:32 -03:00
|
|
|
return '|'.join(['%s.%s' % (module, name) for name in self.name.split('|')])
|
2021-03-31 01:17:26 -03:00
|
|
|
else:
|
|
|
|
name = []
|
|
|
|
for n in self._name_.split('|'):
|
2022-01-17 11:18:13 -04:00
|
|
|
if n[0].isdigit():
|
2021-03-31 01:17:26 -03:00
|
|
|
name.append(n)
|
|
|
|
else:
|
|
|
|
name.append('%s.%s' % (module, n))
|
|
|
|
return '|'.join(name)
|
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
def global_str(self):
|
|
|
|
"""
|
|
|
|
use enum_name instead of class.enum_name
|
|
|
|
"""
|
|
|
|
if self._name_ is None:
|
2022-05-23 12:56:07 -03:00
|
|
|
cls_name = self.__class__.__name__
|
2022-01-17 11:18:13 -04:00
|
|
|
return "%s(%r)" % (cls_name, self._value_)
|
|
|
|
else:
|
|
|
|
return self._name_
|
2021-03-31 01:17:26 -03:00
|
|
|
|
2022-01-17 11:18:13 -04:00
|
|
|
def global_enum(cls, update_str=False):
|
2021-03-31 01:17:26 -03:00
|
|
|
"""
|
|
|
|
decorator that makes the repr() of an enum member reference its module
|
|
|
|
instead of its class; also exports all members to the enum's module's
|
|
|
|
global namespace
|
|
|
|
"""
|
|
|
|
if issubclass(cls, Flag):
|
|
|
|
cls.__repr__ = global_flag_repr
|
|
|
|
else:
|
|
|
|
cls.__repr__ = global_enum_repr
|
2022-01-17 11:18:13 -04:00
|
|
|
if not issubclass(cls, ReprEnum) or update_str:
|
|
|
|
cls.__str__ = global_str
|
2021-03-31 01:17:26 -03:00
|
|
|
sys.modules[cls.__module__].__dict__.update(cls.__members__)
|
|
|
|
return cls
|
2021-04-21 14:20:44 -03:00
|
|
|
|
|
|
|
def _simple_enum(etype=Enum, *, boundary=None, use_args=None):
|
|
|
|
"""
|
|
|
|
Class decorator that converts a normal class into an :class:`Enum`. No
|
|
|
|
safety checks are done, and some advanced behavior (such as
|
|
|
|
:func:`__init_subclass__`) is not available. Enum creation can be faster
|
2023-10-16 17:37:54 -03:00
|
|
|
using :func:`_simple_enum`.
|
2021-04-21 14:20:44 -03:00
|
|
|
|
|
|
|
>>> from enum import Enum, _simple_enum
|
|
|
|
>>> @_simple_enum(Enum)
|
|
|
|
... class Color:
|
|
|
|
... RED = auto()
|
|
|
|
... GREEN = auto()
|
|
|
|
... BLUE = auto()
|
|
|
|
>>> Color
|
|
|
|
<enum 'Color'>
|
|
|
|
"""
|
|
|
|
def convert_class(cls):
|
|
|
|
nonlocal use_args
|
|
|
|
cls_name = cls.__name__
|
|
|
|
if use_args is None:
|
|
|
|
use_args = etype._use_args_
|
|
|
|
__new__ = cls.__dict__.get('__new__')
|
|
|
|
if __new__ is not None:
|
|
|
|
new_member = __new__.__func__
|
|
|
|
else:
|
|
|
|
new_member = etype._member_type_.__new__
|
|
|
|
attrs = {}
|
|
|
|
body = {}
|
|
|
|
if __new__ is not None:
|
|
|
|
body['__new_member__'] = new_member
|
|
|
|
body['_new_member_'] = new_member
|
|
|
|
body['_use_args_'] = use_args
|
|
|
|
body['_generate_next_value_'] = gnv = etype._generate_next_value_
|
|
|
|
body['_member_names_'] = member_names = []
|
|
|
|
body['_member_map_'] = member_map = {}
|
|
|
|
body['_value2member_map_'] = value2member_map = {}
|
2023-12-05 12:27:36 -04:00
|
|
|
body['_unhashable_values_'] = unhashable_values = []
|
|
|
|
body['_unhashable_values_map_'] = {}
|
2021-04-21 14:20:44 -03:00
|
|
|
body['_member_type_'] = member_type = etype._member_type_
|
2022-01-17 11:18:13 -04:00
|
|
|
body['_value_repr_'] = etype._value_repr_
|
2021-04-21 14:20:44 -03:00
|
|
|
if issubclass(etype, Flag):
|
|
|
|
body['_boundary_'] = boundary or etype._boundary_
|
|
|
|
body['_flag_mask_'] = None
|
|
|
|
body['_all_bits_'] = None
|
2023-04-13 12:24:33 -03:00
|
|
|
body['_singles_mask_'] = None
|
2021-04-21 14:20:44 -03:00
|
|
|
body['_inverted_'] = None
|
2022-01-22 22:27:52 -04:00
|
|
|
body['__or__'] = Flag.__or__
|
|
|
|
body['__xor__'] = Flag.__xor__
|
|
|
|
body['__and__'] = Flag.__and__
|
|
|
|
body['__ror__'] = Flag.__ror__
|
|
|
|
body['__rxor__'] = Flag.__rxor__
|
|
|
|
body['__rand__'] = Flag.__rand__
|
|
|
|
body['__invert__'] = Flag.__invert__
|
2021-04-21 14:20:44 -03:00
|
|
|
for name, obj in cls.__dict__.items():
|
|
|
|
if name in ('__dict__', '__weakref__'):
|
|
|
|
continue
|
|
|
|
if _is_dunder(name) or _is_private(cls_name, name) or _is_sunder(name) or _is_descriptor(obj):
|
|
|
|
body[name] = obj
|
|
|
|
else:
|
|
|
|
attrs[name] = obj
|
|
|
|
if cls.__dict__.get('__doc__') is None:
|
|
|
|
body['__doc__'] = 'An enumeration.'
|
|
|
|
#
|
|
|
|
# double check that repr and friends are not the mixin's or various
|
|
|
|
# things break (such as pickle)
|
|
|
|
# however, if the method is defined in the Enum itself, don't replace
|
|
|
|
# it
|
|
|
|
enum_class = type(cls_name, (etype, ), body, boundary=boundary, _simple=True)
|
|
|
|
for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'):
|
2022-01-17 11:18:13 -04:00
|
|
|
if name not in body:
|
2022-07-17 22:51:04 -03:00
|
|
|
# check for mixin overrides before replacing
|
|
|
|
enum_method = getattr(etype, name)
|
|
|
|
found_method = getattr(enum_class, name)
|
|
|
|
object_method = getattr(object, name)
|
|
|
|
data_type_method = getattr(member_type, name)
|
|
|
|
if found_method in (data_type_method, object_method):
|
|
|
|
setattr(enum_class, name, enum_method)
|
2021-04-21 14:20:44 -03:00
|
|
|
gnv_last_values = []
|
|
|
|
if issubclass(enum_class, Flag):
|
|
|
|
# Flag / IntFlag
|
|
|
|
single_bits = multi_bits = 0
|
|
|
|
for name, value in attrs.items():
|
|
|
|
if isinstance(value, auto) and auto.value is _auto_null:
|
|
|
|
value = gnv(name, 1, len(member_names), gnv_last_values)
|
2024-04-09 15:31:07 -03:00
|
|
|
# create basic member (possibly isolate value for alias check)
|
|
|
|
if use_args:
|
|
|
|
if not isinstance(value, tuple):
|
|
|
|
value = (value, )
|
|
|
|
member = new_member(enum_class, *value)
|
|
|
|
value = value[0]
|
|
|
|
else:
|
|
|
|
member = new_member(enum_class)
|
|
|
|
if __new__ is None:
|
|
|
|
member._value_ = value
|
|
|
|
# now check if alias
|
|
|
|
try:
|
|
|
|
contained = value2member_map.get(member._value_)
|
|
|
|
except TypeError:
|
|
|
|
contained = None
|
|
|
|
if member._value_ in unhashable_values:
|
|
|
|
for m in enum_class:
|
|
|
|
if m._value_ == member._value_:
|
|
|
|
contained = m
|
|
|
|
break
|
|
|
|
if contained is not None:
|
2021-04-21 14:20:44 -03:00
|
|
|
# an alias to an existing member
|
2024-04-09 15:31:07 -03:00
|
|
|
contained._add_alias_(name)
|
2021-04-21 14:20:44 -03:00
|
|
|
else:
|
2024-04-09 15:31:07 -03:00
|
|
|
# finish creating member
|
2021-04-21 14:20:44 -03:00
|
|
|
member._name_ = name
|
|
|
|
member.__objclass__ = enum_class
|
|
|
|
member.__init__(value)
|
|
|
|
member._sort_order_ = len(member_names)
|
2023-12-05 12:27:36 -04:00
|
|
|
if name not in ('name', 'value'):
|
|
|
|
setattr(enum_class, name, member)
|
|
|
|
member_map[name] = member
|
|
|
|
else:
|
|
|
|
enum_class._add_member_(name, member)
|
2021-04-21 14:20:44 -03:00
|
|
|
value2member_map[value] = member
|
|
|
|
if _is_single_bit(value):
|
|
|
|
# not a multi-bit alias, record in _member_names_ and _flag_mask_
|
|
|
|
member_names.append(name)
|
|
|
|
single_bits |= value
|
|
|
|
else:
|
|
|
|
multi_bits |= value
|
|
|
|
gnv_last_values.append(value)
|
2023-04-13 12:24:33 -03:00
|
|
|
enum_class._flag_mask_ = single_bits | multi_bits
|
|
|
|
enum_class._singles_mask_ = single_bits
|
2021-04-21 14:20:44 -03:00
|
|
|
enum_class._all_bits_ = 2 ** ((single_bits|multi_bits).bit_length()) - 1
|
|
|
|
# set correct __iter__
|
|
|
|
member_list = [m._value_ for m in enum_class]
|
|
|
|
if member_list != sorted(member_list):
|
|
|
|
enum_class._iter_member_ = enum_class._iter_member_by_def_
|
|
|
|
else:
|
|
|
|
# Enum / IntEnum / StrEnum
|
|
|
|
for name, value in attrs.items():
|
|
|
|
if isinstance(value, auto):
|
|
|
|
if value.value is _auto_null:
|
|
|
|
value.value = gnv(name, 1, len(member_names), gnv_last_values)
|
|
|
|
value = value.value
|
2024-04-09 15:31:07 -03:00
|
|
|
# create basic member (possibly isolate value for alias check)
|
|
|
|
if use_args:
|
|
|
|
if not isinstance(value, tuple):
|
|
|
|
value = (value, )
|
|
|
|
member = new_member(enum_class, *value)
|
|
|
|
value = value[0]
|
|
|
|
else:
|
|
|
|
member = new_member(enum_class)
|
|
|
|
if __new__ is None:
|
|
|
|
member._value_ = value
|
|
|
|
# now check if alias
|
2023-12-05 12:27:36 -04:00
|
|
|
try:
|
2024-04-09 15:31:07 -03:00
|
|
|
contained = value2member_map.get(member._value_)
|
2023-12-05 12:27:36 -04:00
|
|
|
except TypeError:
|
2024-04-09 15:31:07 -03:00
|
|
|
contained = None
|
|
|
|
if member._value_ in unhashable_values:
|
|
|
|
for m in enum_class:
|
|
|
|
if m._value_ == member._value_:
|
|
|
|
contained = m
|
|
|
|
break
|
|
|
|
if contained is not None:
|
2021-04-21 14:20:44 -03:00
|
|
|
# an alias to an existing member
|
2024-04-09 15:31:07 -03:00
|
|
|
contained._add_alias_(name)
|
2021-04-21 14:20:44 -03:00
|
|
|
else:
|
2024-04-09 15:31:07 -03:00
|
|
|
# finish creating member
|
2021-04-21 14:20:44 -03:00
|
|
|
member._name_ = name
|
|
|
|
member.__objclass__ = enum_class
|
|
|
|
member.__init__(value)
|
|
|
|
member._sort_order_ = len(member_names)
|
2023-12-05 12:27:36 -04:00
|
|
|
if name not in ('name', 'value'):
|
|
|
|
setattr(enum_class, name, member)
|
|
|
|
member_map[name] = member
|
|
|
|
else:
|
|
|
|
enum_class._add_member_(name, member)
|
2021-04-21 14:20:44 -03:00
|
|
|
member_names.append(name)
|
|
|
|
gnv_last_values.append(value)
|
2023-12-05 12:27:36 -04:00
|
|
|
try:
|
|
|
|
# This may fail if value is not hashable. We can't add the value
|
|
|
|
# to the map, and by-value lookups for this value will be
|
|
|
|
# linear.
|
|
|
|
enum_class._value2member_map_.setdefault(value, member)
|
|
|
|
except TypeError:
|
|
|
|
# keep track of the value in a list so containment checks are quick
|
|
|
|
enum_class._unhashable_values_.append(value)
|
|
|
|
enum_class._unhashable_values_map_.setdefault(name, []).append(value)
|
2021-04-21 14:20:44 -03:00
|
|
|
if '__new__' in body:
|
|
|
|
enum_class.__new_member__ = enum_class.__new__
|
|
|
|
enum_class.__new__ = Enum.__new__
|
|
|
|
return enum_class
|
|
|
|
return convert_class
|
|
|
|
|
2021-06-09 13:03:55 -03:00
|
|
|
@_simple_enum(StrEnum)
|
|
|
|
class EnumCheck:
|
|
|
|
"""
|
|
|
|
various conditions to check an enumeration for
|
|
|
|
"""
|
|
|
|
CONTINUOUS = "no skipped integer values"
|
|
|
|
NAMED_FLAGS = "multi-flag aliases may not contain unnamed flags"
|
|
|
|
UNIQUE = "one name per value"
|
|
|
|
CONTINUOUS, NAMED_FLAGS, UNIQUE = EnumCheck
|
|
|
|
|
|
|
|
|
|
|
|
class verify:
|
|
|
|
"""
|
|
|
|
Check an enumeration for various constraints. (see EnumCheck)
|
|
|
|
"""
|
|
|
|
def __init__(self, *checks):
|
|
|
|
self.checks = checks
|
|
|
|
def __call__(self, enumeration):
|
|
|
|
checks = self.checks
|
|
|
|
cls_name = enumeration.__name__
|
|
|
|
if Flag is not None and issubclass(enumeration, Flag):
|
|
|
|
enum_type = 'flag'
|
|
|
|
elif issubclass(enumeration, Enum):
|
|
|
|
enum_type = 'enum'
|
|
|
|
else:
|
|
|
|
raise TypeError("the 'verify' decorator only works with Enum and Flag")
|
|
|
|
for check in checks:
|
|
|
|
if check is UNIQUE:
|
|
|
|
# check for duplicate names
|
|
|
|
duplicates = []
|
|
|
|
for name, member in enumeration.__members__.items():
|
|
|
|
if name != member.name:
|
|
|
|
duplicates.append((name, member.name))
|
|
|
|
if duplicates:
|
|
|
|
alias_details = ', '.join(
|
|
|
|
["%s -> %s" % (alias, name) for (alias, name) in duplicates])
|
|
|
|
raise ValueError('aliases found in %r: %s' %
|
|
|
|
(enumeration, alias_details))
|
|
|
|
elif check is CONTINUOUS:
|
|
|
|
values = set(e.value for e in enumeration)
|
|
|
|
if len(values) < 2:
|
|
|
|
continue
|
|
|
|
low, high = min(values), max(values)
|
|
|
|
missing = []
|
|
|
|
if enum_type == 'flag':
|
|
|
|
# check for powers of two
|
|
|
|
for i in range(_high_bit(low)+1, _high_bit(high)):
|
|
|
|
if 2**i not in values:
|
|
|
|
missing.append(2**i)
|
|
|
|
elif enum_type == 'enum':
|
|
|
|
# check for powers of one
|
|
|
|
for i in range(low+1, high):
|
|
|
|
if i not in values:
|
|
|
|
missing.append(i)
|
|
|
|
else:
|
|
|
|
raise Exception('verify: unknown type %r' % enum_type)
|
|
|
|
if missing:
|
2021-06-11 06:44:43 -03:00
|
|
|
raise ValueError(('invalid %s %r: missing values %s' % (
|
2021-06-09 13:03:55 -03:00
|
|
|
enum_type, cls_name, ', '.join((str(m) for m in missing)))
|
2021-06-11 06:44:43 -03:00
|
|
|
)[:256])
|
|
|
|
# limit max length to protect against DOS attacks
|
2021-06-09 13:03:55 -03:00
|
|
|
elif check is NAMED_FLAGS:
|
|
|
|
# examine each alias and check for unnamed flags
|
|
|
|
member_names = enumeration._member_names_
|
|
|
|
member_values = [m.value for m in enumeration]
|
2021-06-11 06:44:43 -03:00
|
|
|
missing_names = []
|
|
|
|
missing_value = 0
|
2021-06-09 13:03:55 -03:00
|
|
|
for name, alias in enumeration._member_map_.items():
|
|
|
|
if name in member_names:
|
|
|
|
# not an alias
|
|
|
|
continue
|
2022-11-08 16:00:19 -04:00
|
|
|
if alias.value < 0:
|
|
|
|
# negative numbers are not checked
|
|
|
|
continue
|
2021-06-09 13:03:55 -03:00
|
|
|
values = list(_iter_bits_lsb(alias.value))
|
|
|
|
missed = [v for v in values if v not in member_values]
|
|
|
|
if missed:
|
2021-06-11 06:44:43 -03:00
|
|
|
missing_names.append(name)
|
2023-09-23 15:31:17 -03:00
|
|
|
for val in missed:
|
|
|
|
missing_value |= val
|
2021-06-11 06:44:43 -03:00
|
|
|
if missing_names:
|
|
|
|
if len(missing_names) == 1:
|
|
|
|
alias = 'alias %s is missing' % missing_names[0]
|
|
|
|
else:
|
|
|
|
alias = 'aliases %s and %s are missing' % (
|
|
|
|
', '.join(missing_names[:-1]), missing_names[-1]
|
|
|
|
)
|
|
|
|
if _is_single_bit(missing_value):
|
|
|
|
value = 'value 0x%x' % missing_value
|
|
|
|
else:
|
|
|
|
value = 'combined values of 0x%x' % missing_value
|
2021-06-09 13:03:55 -03:00
|
|
|
raise ValueError(
|
2021-06-15 22:51:19 -03:00
|
|
|
'invalid Flag %r: %s %s [use enum.show_flag_values(value) for details]'
|
2021-06-11 06:44:43 -03:00
|
|
|
% (cls_name, alias, value)
|
2021-06-09 13:03:55 -03:00
|
|
|
)
|
|
|
|
return enumeration
|
|
|
|
|
2021-04-21 14:20:44 -03:00
|
|
|
def _test_simple_enum(checked_enum, simple_enum):
|
|
|
|
"""
|
|
|
|
A function that can be used to test an enum created with :func:`_simple_enum`
|
|
|
|
against the version created by subclassing :class:`Enum`::
|
|
|
|
|
|
|
|
>>> from enum import Enum, _simple_enum, _test_simple_enum
|
|
|
|
>>> @_simple_enum(Enum)
|
|
|
|
... class Color:
|
|
|
|
... RED = auto()
|
|
|
|
... GREEN = auto()
|
|
|
|
... BLUE = auto()
|
|
|
|
>>> class CheckedColor(Enum):
|
|
|
|
... RED = auto()
|
|
|
|
... GREEN = auto()
|
|
|
|
... BLUE = auto()
|
|
|
|
>>> _test_simple_enum(CheckedColor, Color)
|
|
|
|
|
|
|
|
If differences are found, a :exc:`TypeError` is raised.
|
|
|
|
"""
|
|
|
|
failed = []
|
|
|
|
if checked_enum.__dict__ != simple_enum.__dict__:
|
|
|
|
checked_dict = checked_enum.__dict__
|
|
|
|
checked_keys = list(checked_dict.keys())
|
|
|
|
simple_dict = simple_enum.__dict__
|
|
|
|
simple_keys = list(simple_dict.keys())
|
|
|
|
member_names = set(
|
|
|
|
list(checked_enum._member_map_.keys())
|
|
|
|
+ list(simple_enum._member_map_.keys())
|
|
|
|
)
|
|
|
|
for key in set(checked_keys + simple_keys):
|
2024-03-26 12:18:17 -03:00
|
|
|
if key in ('__module__', '_member_map_', '_value2member_map_', '__doc__',
|
|
|
|
'__static_attributes__'):
|
2022-01-17 11:18:13 -04:00
|
|
|
# keys known to be different, or very long
|
2021-04-21 14:20:44 -03:00
|
|
|
continue
|
|
|
|
elif key in member_names:
|
|
|
|
# members are checked below
|
|
|
|
continue
|
|
|
|
elif key not in simple_keys:
|
|
|
|
failed.append("missing key: %r" % (key, ))
|
|
|
|
elif key not in checked_keys:
|
|
|
|
failed.append("extra key: %r" % (key, ))
|
|
|
|
else:
|
|
|
|
checked_value = checked_dict[key]
|
|
|
|
simple_value = simple_dict[key]
|
2022-08-30 15:11:44 -03:00
|
|
|
if callable(checked_value) or isinstance(checked_value, bltns.property):
|
2021-04-21 14:20:44 -03:00
|
|
|
continue
|
|
|
|
if key == '__doc__':
|
|
|
|
# remove all spaces/tabs
|
|
|
|
compressed_checked_value = checked_value.replace(' ','').replace('\t','')
|
|
|
|
compressed_simple_value = simple_value.replace(' ','').replace('\t','')
|
|
|
|
if compressed_checked_value != compressed_simple_value:
|
|
|
|
failed.append("%r:\n %s\n %s" % (
|
|
|
|
key,
|
|
|
|
"checked -> %r" % (checked_value, ),
|
|
|
|
"simple -> %r" % (simple_value, ),
|
|
|
|
))
|
|
|
|
elif checked_value != simple_value:
|
|
|
|
failed.append("%r:\n %s\n %s" % (
|
|
|
|
key,
|
|
|
|
"checked -> %r" % (checked_value, ),
|
|
|
|
"simple -> %r" % (simple_value, ),
|
|
|
|
))
|
|
|
|
failed.sort()
|
|
|
|
for name in member_names:
|
|
|
|
failed_member = []
|
|
|
|
if name not in simple_keys:
|
|
|
|
failed.append('missing member from simple enum: %r' % name)
|
|
|
|
elif name not in checked_keys:
|
|
|
|
failed.append('extra member in simple enum: %r' % name)
|
|
|
|
else:
|
|
|
|
checked_member_dict = checked_enum[name].__dict__
|
|
|
|
checked_member_keys = list(checked_member_dict.keys())
|
|
|
|
simple_member_dict = simple_enum[name].__dict__
|
|
|
|
simple_member_keys = list(simple_member_dict.keys())
|
|
|
|
for key in set(checked_member_keys + simple_member_keys):
|
2021-04-23 23:08:22 -03:00
|
|
|
if key in ('__module__', '__objclass__', '_inverted_'):
|
|
|
|
# keys known to be different or absent
|
2021-04-21 14:20:44 -03:00
|
|
|
continue
|
|
|
|
elif key not in simple_member_keys:
|
|
|
|
failed_member.append("missing key %r not in the simple enum member %r" % (key, name))
|
|
|
|
elif key not in checked_member_keys:
|
|
|
|
failed_member.append("extra key %r in simple enum member %r" % (key, name))
|
|
|
|
else:
|
|
|
|
checked_value = checked_member_dict[key]
|
|
|
|
simple_value = simple_member_dict[key]
|
|
|
|
if checked_value != simple_value:
|
|
|
|
failed_member.append("%r:\n %s\n %s" % (
|
|
|
|
key,
|
|
|
|
"checked member -> %r" % (checked_value, ),
|
|
|
|
"simple member -> %r" % (simple_value, ),
|
|
|
|
))
|
|
|
|
if failed_member:
|
|
|
|
failed.append('%r member mismatch:\n %s' % (
|
|
|
|
name, '\n '.join(failed_member),
|
|
|
|
))
|
|
|
|
for method in (
|
|
|
|
'__str__', '__repr__', '__reduce_ex__', '__format__',
|
|
|
|
'__getnewargs_ex__', '__getnewargs__', '__reduce_ex__', '__reduce__'
|
|
|
|
):
|
|
|
|
if method in simple_keys and method in checked_keys:
|
|
|
|
# cannot compare functions, and it exists in both, so we're good
|
|
|
|
continue
|
|
|
|
elif method not in simple_keys and method not in checked_keys:
|
|
|
|
# method is inherited -- check it out
|
|
|
|
checked_method = getattr(checked_enum, method, None)
|
|
|
|
simple_method = getattr(simple_enum, method, None)
|
|
|
|
if hasattr(checked_method, '__func__'):
|
|
|
|
checked_method = checked_method.__func__
|
|
|
|
simple_method = simple_method.__func__
|
|
|
|
if checked_method != simple_method:
|
|
|
|
failed.append("%r: %-30s %s" % (
|
|
|
|
method,
|
|
|
|
"checked -> %r" % (checked_method, ),
|
|
|
|
"simple -> %r" % (simple_method, ),
|
|
|
|
))
|
|
|
|
else:
|
|
|
|
# if the method existed in only one of the enums, it will have been caught
|
|
|
|
# in the first checks above
|
|
|
|
pass
|
|
|
|
if failed:
|
|
|
|
raise TypeError('enum mismatch:\n %s' % '\n '.join(failed))
|
|
|
|
|
|
|
|
def _old_convert_(etype, name, module, filter, source=None, *, boundary=None):
|
|
|
|
"""
|
|
|
|
Create a new Enum subclass that replaces a collection of global constants
|
|
|
|
"""
|
|
|
|
# convert all constants from source (or module) that pass filter() to
|
|
|
|
# a new Enum called name, and export the enum and its members back to
|
|
|
|
# module;
|
|
|
|
# also, replace the __reduce_ex__ method so unpickling works in
|
|
|
|
# previous Python versions
|
|
|
|
module_globals = sys.modules[module].__dict__
|
|
|
|
if source:
|
|
|
|
source = source.__dict__
|
|
|
|
else:
|
|
|
|
source = module_globals
|
|
|
|
# _value2member_map_ is populated in the same order every time
|
|
|
|
# for a consistent reverse mapping of number to name when there
|
|
|
|
# are multiple names for the same number.
|
|
|
|
members = [
|
|
|
|
(name, value)
|
|
|
|
for name, value in source.items()
|
|
|
|
if filter(name)]
|
|
|
|
try:
|
|
|
|
# sort by value
|
|
|
|
members.sort(key=lambda t: (t[1], t[0]))
|
|
|
|
except TypeError:
|
|
|
|
# unless some values aren't comparable, in which case sort by name
|
|
|
|
members.sort(key=lambda t: t[0])
|
|
|
|
cls = etype(name, members, module=module, boundary=boundary or KEEP)
|
|
|
|
return cls
|
2022-01-17 11:18:13 -04:00
|
|
|
|
|
|
|
_stdlib_enums = IntEnum, StrEnum, IntFlag
|