Skip to content

Commit 0b9c90f

Browse files
authored
Update enum from v3.14.2 (#6932)
--------- Co-authored-by: CPython Developers <>
1 parent 97861c6 commit 0b9c90f

2 files changed

Lines changed: 44 additions & 81 deletions

File tree

Lib/enum.py

Lines changed: 18 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import sys
22
import builtins as bltns
3-
from functools import partial
43
from types import MappingProxyType, DynamicClassAttribute
54

65

@@ -38,7 +37,7 @@ def _is_descriptor(obj):
3837
"""
3938
Returns True if obj is a descriptor, False otherwise.
4039
"""
41-
return not isinstance(obj, partial) and (
40+
return (
4241
hasattr(obj, '__get__') or
4342
hasattr(obj, '__set__') or
4443
hasattr(obj, '__delete__')
@@ -151,18 +150,6 @@ def bin(num, max_bits=None):
151150
digits = (sign[-1] * max_bits + digits)[-max_bits:]
152151
return "%s %s" % (sign, digits)
153152

154-
def _dedent(text):
155-
"""
156-
Like textwrap.dedent. Rewritten because we cannot import textwrap.
157-
"""
158-
lines = text.split('\n')
159-
for i, ch in enumerate(lines[0]):
160-
if ch != ' ':
161-
break
162-
for j, l in enumerate(lines):
163-
lines[j] = l[i:]
164-
return '\n'.join(lines)
165-
166153
class _not_given:
167154
def __repr__(self):
168155
return('<not given>')
@@ -208,7 +195,7 @@ def __get__(self, instance, ownerclass=None):
208195
# use previous enum.property
209196
return self.fget(instance)
210197
elif self._attr_type == 'attr':
211-
# look up previous attibute
198+
# look up previous attribute
212199
return getattr(self._cls_type, self.name)
213200
elif self._attr_type == 'desc':
214201
# use previous descriptor
@@ -406,12 +393,6 @@ def __setitem__(self, key, value):
406393
elif isinstance(value, nonmember):
407394
# unwrap value here; it won't be processed by the below `else`
408395
value = value.value
409-
elif isinstance(value, partial):
410-
import warnings
411-
warnings.warn('functools.partial will be a method descriptor '
412-
'in future Python versions; wrap it in '
413-
'enum.member() if you want to preserve the '
414-
'old behavior', FutureWarning, stacklevel=2)
415396
elif _is_descriptor(value):
416397
pass
417398
elif self._cls_name is not None and _is_internal_class(self._cls_name, value):
@@ -1103,6 +1084,21 @@ def _add_member_(cls, name, member):
11031084
# now add to _member_map_ (even aliases)
11041085
cls._member_map_[name] = member
11051086

1087+
@property
1088+
def __signature__(cls):
1089+
from inspect import Parameter, Signature
1090+
if cls._member_names_:
1091+
return Signature([Parameter('values', Parameter.VAR_POSITIONAL)])
1092+
else:
1093+
return Signature([Parameter('new_class_name', Parameter.POSITIONAL_ONLY),
1094+
Parameter('names', Parameter.POSITIONAL_OR_KEYWORD),
1095+
Parameter('module', Parameter.KEYWORD_ONLY, default=None),
1096+
Parameter('qualname', Parameter.KEYWORD_ONLY, default=None),
1097+
Parameter('type', Parameter.KEYWORD_ONLY, default=None),
1098+
Parameter('start', Parameter.KEYWORD_ONLY, default=1),
1099+
Parameter('boundary', Parameter.KEYWORD_ONLY, default=None)])
1100+
1101+
11061102
EnumMeta = EnumType # keep EnumMeta name for backwards compatibility
11071103

11081104

@@ -1146,13 +1142,6 @@ class Enum(metaclass=EnumType):
11461142
attributes -- see the documentation for details.
11471143
"""
11481144

1149-
@classmethod
1150-
def __signature__(cls):
1151-
if cls._member_names_:
1152-
return '(*values)'
1153-
else:
1154-
return '(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)'
1155-
11561145
def __new__(cls, value):
11571146
# all enum instances are actually created during class construction
11581147
# without calling this method; this method is called by the metaclass'
@@ -1214,9 +1203,6 @@ def __new__(cls, value):
12141203
exc = None
12151204
ve_exc = None
12161205

1217-
def __init__(self, *args, **kwds):
1218-
pass
1219-
12201206
def _add_alias_(self, name):
12211207
self.__class__._add_member_(name, self)
12221208

@@ -2041,8 +2027,7 @@ def _test_simple_enum(checked_enum, simple_enum):
20412027
... RED = auto()
20422028
... GREEN = auto()
20432029
... BLUE = auto()
2044-
... # TODO: RUSTPYTHON
2045-
>>> _test_simple_enum(CheckedColor, Color) # doctest: +SKIP
2030+
>>> _test_simple_enum(CheckedColor, Color)
20462031
20472032
If differences are found, a :exc:`TypeError` is raised.
20482033
"""

Lib/test/test_enum.py

Lines changed: 26 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import builtins as bltns
1212
from collections import OrderedDict
1313
from datetime import date
14-
from functools import partial
1514
from enum import Enum, EnumMeta, IntEnum, StrEnum, EnumType, Flag, IntFlag, unique, auto
1615
from enum import STRICT, CONFORM, EJECT, KEEP, _simple_enum, _test_simple_enum
1716
from enum import verify, UNIQUE, CONTINUOUS, NAMED_FLAGS, ReprEnum
@@ -20,7 +19,8 @@
2019
from pickle import dumps, loads, PicklingError, HIGHEST_PROTOCOL
2120
from test import support
2221
from test.support import ALWAYS_EQ, REPO_ROOT
23-
from test.support import threading_helper
22+
from test.support import threading_helper, cpython_only
23+
from test.support.import_helper import ensure_lazy_imports
2424
from datetime import timedelta
2525

2626
python_version = sys.version_info[:2]
@@ -434,9 +434,9 @@ class Season(self.enum_type):
434434
def spam(cls):
435435
pass
436436
#
437-
self.assertTrue(hasattr(Season, 'spam'))
437+
self.assertHasAttr(Season, 'spam')
438438
del Season.spam
439-
self.assertFalse(hasattr(Season, 'spam'))
439+
self.assertNotHasAttr(Season, 'spam')
440440
#
441441
with self.assertRaises(AttributeError):
442442
del Season.SPRING
@@ -445,8 +445,7 @@ def spam(cls):
445445
with self.assertRaises(AttributeError):
446446
del Season.SPRING.name
447447

448-
@unittest.expectedFailure # TODO: RUSTPYTHON
449-
# RuntimeError: Error calling __set_name__ on '_proto_member' instance failed in 'BadSuper'
448+
@unittest.expectedFailure # TODO: RUSTPYTHON; RuntimeError: Error calling __set_name__ on '_proto_member' instance failed in 'BadSuper'
450449
def test_bad_new_super(self):
451450
with self.assertRaisesRegex(
452451
TypeError,
@@ -659,9 +658,6 @@ def __repr__(self):
659658
self.assertEqual(str(Generic.item), 'item.test')
660659

661660
def test_overridden_str(self):
662-
# TODO: RUSTPYTHON, format(NS.first) does not use __str__
663-
if self.__class__ in (TestIntFlagFunction, TestIntFlagClass, TestIntEnumFunction, TestIntEnumClass, TestMinimalFloatFunction, TestMinimalFloatClass):
664-
self.skipTest("format(NS.first) does not use __str__")
665661
NS = self.NewStrEnum
666662
self.assertEqual(str(NS.first), NS.first.name.upper())
667663
self.assertEqual(format(NS.first), NS.first.name.upper())
@@ -1544,22 +1540,6 @@ class Inner(Enum):
15441540
[Outer.a, Outer.b, Outer.Inner],
15451541
)
15461542

1547-
# TODO: RUSTPYTHON
1548-
# AssertionError: FutureWarning not triggered
1549-
@unittest.expectedFailure
1550-
def test_partial(self):
1551-
def func(a, b=5):
1552-
return a, b
1553-
with self.assertWarnsRegex(FutureWarning, r'partial.*enum\.member') as cm:
1554-
class E(Enum):
1555-
a = 1
1556-
b = partial(func)
1557-
self.assertEqual(cm.filename, __file__)
1558-
self.assertIsInstance(E.b, partial)
1559-
self.assertEqual(E.b(2), (2, 5))
1560-
with self.assertWarnsRegex(FutureWarning, 'partial'):
1561-
self.assertEqual(E.a.b(2), (2, 5))
1562-
15631543
def test_enum_with_value_name(self):
15641544
class Huh(Enum):
15651545
name = 1
@@ -1769,7 +1749,7 @@ class ThreePart(Enum):
17691749
self.assertIs(ThreePart((3, 3.0, 'three')), ThreePart.THREE)
17701750
self.assertIs(ThreePart(3, 3.0, 'three'), ThreePart.THREE)
17711751

1772-
@unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: <test.test_enum.IntStooges object at 0x55c70c38a240> is not <IntStooges.MOE: 3>
1752+
@unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: <test.test_enum.IntStooges object at 0x55c70c38a240> is not <IntStooges.MOE: 3>
17731753
@reraise_if_not_enum(IntStooges)
17741754
def test_intenum_from_bytes(self):
17751755
self.assertIs(IntStooges.from_bytes(b'\x00\x03', 'big'), IntStooges.MOE)
@@ -1923,8 +1903,7 @@ def test_wrong_inheritance_order(self):
19231903
class Wrong(Enum, str):
19241904
NotHere = 'error before this point'
19251905

1926-
@unittest.expectedFailure # TODO: RUSTPYTHON
1927-
# RuntimeError: Error calling __set_name__ on '_proto_member' instance INVALID in 'RgbColor'
1906+
@unittest.expectedFailure # TODO: RUSTPYTHON; RuntimeError: Error calling __set_name__ on '_proto_member' instance INVALID in 'RgbColor'
19281907
def test_raise_custom_error_on_creation(self):
19291908
class InvalidRgbColorError(ValueError):
19301909
def __init__(self, r, g, b):
@@ -2612,8 +2591,7 @@ class Test(Base2):
26122591
self.assertEqual(Test.flash.flash, 'flashy dynamic')
26132592
self.assertEqual(Test.flash.value, 1)
26142593

2615-
@unittest.expectedFailure # TODO: RUSTPYTHON
2616-
# RuntimeError: Error calling __set_name__ on '_proto_member' instance grene in 'Color'
2594+
@unittest.expectedFailure # TODO: RUSTPYTHON; RuntimeError: Error calling __set_name__ on '_proto_member' instance grene in 'Color'
26172595
def test_no_duplicates(self):
26182596
class UniqueEnum(Enum):
26192597
def __init__(self, *args):
@@ -2678,12 +2656,12 @@ def __new__(cls, value, period):
26782656
OneDay = day_1
26792657
OneWeek = week_1
26802658
OneMonth = month_1
2681-
self.assertFalse(hasattr(Period, '_ignore_'))
2682-
self.assertFalse(hasattr(Period, 'Period'))
2683-
self.assertFalse(hasattr(Period, 'i'))
2684-
self.assertTrue(isinstance(Period.day_1, timedelta))
2685-
self.assertTrue(Period.month_1 is Period.day_30)
2686-
self.assertTrue(Period.week_4 is Period.day_28)
2659+
self.assertNotHasAttr(Period, '_ignore_')
2660+
self.assertNotHasAttr(Period, 'Period')
2661+
self.assertNotHasAttr(Period, 'i')
2662+
self.assertIsInstance(Period.day_1, timedelta)
2663+
self.assertIs(Period.month_1, Period.day_30)
2664+
self.assertIs(Period.week_4, Period.day_28)
26872665

26882666
def test_nonhash_value(self):
26892667
class AutoNumberInAList(Enum):
@@ -2903,7 +2881,7 @@ class ReformedColor(StrMixin, IntEnum, SomeEnum, AnotherEnum):
29032881
self.assertEqual(str(ReformedColor.BLUE), 'blue')
29042882
self.assertEqual(ReformedColor.RED.behavior(), 'booyah')
29052883
self.assertEqual(ConfusedColor.RED.social(), "what's up?")
2906-
self.assertTrue(issubclass(ReformedColor, int))
2884+
self.assertIsSubclass(ReformedColor, int)
29072885

29082886
def test_multiple_inherited_mixin(self):
29092887
@unique
@@ -2999,8 +2977,7 @@ def test_empty_globals(self):
29992977
local_ls = {}
30002978
exec(code, global_ns, local_ls)
30012979

3002-
@unittest.expectedFailure # TODO: RUSTPYTHON
3003-
# RuntimeError: Error calling __set_name__ on '_proto_member' instance one in 'FirstFailedStrEnum'
2980+
@unittest.expectedFailure # TODO: RUSTPYTHON; RuntimeError: Error calling __set_name__ on '_proto_member' instance one in 'FirstFailedStrEnum'
30042981
def test_strenum(self):
30052982
class GoodStrEnum(StrEnum):
30062983
one = '1'
@@ -3063,7 +3040,7 @@ class ThirdFailedStrEnum(StrEnum):
30633040
one = '1'
30643041
two = b'2', 'ascii', 9
30653042

3066-
@unittest.expectedFailure # TODO: RUSTPYTHON; fails on encoding testing : TypeError: Expected type 'str' but 'builtin_function_or_method' found
3043+
@unittest.expectedFailure # TODO: RUSTPYTHON; fails on encoding testing : TypeError: Expected type 'str' but 'builtin_function_or_method' found
30673044
def test_custom_strenum(self):
30683045
class CustomStrEnum(str, Enum):
30693046
pass
@@ -3125,8 +3102,7 @@ class ThirdFailedStrEnum(CustomStrEnum):
31253102
one = '1'
31263103
two = b'2', 'ascii', 9
31273104

3128-
@unittest.expectedFailure # TODO: RUSTPYTHON
3129-
# RuntimeError: Error calling __set_name__ on '_proto_member' instance key_type in 'Combined'
3105+
@unittest.expectedFailure # TODO: RUSTPYTHON; RuntimeError: Error calling __set_name__ on '_proto_member' instance key_type in 'Combined'
31303106
def test_missing_value_error(self):
31313107
with self.assertRaisesRegex(TypeError, "_value_ not set in __new__"):
31323108
class Combined(str, Enum):
@@ -3413,8 +3389,7 @@ def __new__(cls, c):
34133389
self.assertEqual(FlagFromChar.a, 158456325028528675187087900672)
34143390
self.assertEqual(FlagFromChar.a|1, 158456325028528675187087900673)
34153391

3416-
@unittest.expectedFailure # TODO: RUSTPYTHON
3417-
# RuntimeError: Error calling __set_name__ on '_proto_member' instance A in 'MyEnum'
3392+
@unittest.expectedFailure # TODO: RUSTPYTHON; RuntimeError: Error calling __set_name__ on '_proto_member' instance A in 'MyEnum'
34183393
def test_init_exception(self):
34193394
class Base:
34203395
def __new__(cls, *args):
@@ -4003,7 +3978,7 @@ class Color(StrMixin, AllMixin, Flag):
40033978
self.assertEqual(Color.ALL.value, 7)
40043979
self.assertEqual(str(Color.BLUE), 'blue')
40053980

4006-
@unittest.skip('TODO: RUSTPYTHON; flaky test')
3981+
@unittest.skip("TODO: RUSTPYTHON; flaky test")
40073982
@threading_helper.reap_threads
40083983
@threading_helper.requires_working_threading()
40093984
def test_unique_composite(self):
@@ -4524,7 +4499,7 @@ class Color(StrMixin, AllMixin, IntFlag):
45244499
self.assertEqual(Color.ALL.value, 7)
45254500
self.assertEqual(str(Color.BLUE), 'blue')
45264501

4527-
@unittest.skip('TODO: RUSTPYTHON; flaky test')
4502+
@unittest.skip("TODO: RUSTPYTHON; flaky test")
45284503
@threading_helper.reap_threads
45294504
@threading_helper.requires_working_threading()
45304505
def test_unique_composite(self):
@@ -5073,7 +5048,7 @@ class Color(Enum):
50735048
MAGENTA = 2
50745049
YELLOW = 3
50755050

5076-
@unittest.expectedFailure # TODO: RUSTPYTHON
5051+
@unittest.expectedFailure # TODO: RUSTPYTHON; | is a read-only view of the internal mapping.
50775052
def test_pydoc(self):
50785053
# indirectly test __objclass__
50795054
if StrEnum.__doc__ is None:
@@ -5185,7 +5160,6 @@ def test_inspect_classify_class_attrs(self):
51855160
if failed:
51865161
self.fail("result does not equal expected, see print above")
51875162

5188-
@unittest.expectedFailure # TODO: RUSTPYTHON; Enum.__signature__ is @classmethod instead of @property
51895163
def test_inspect_signatures(self):
51905164
from inspect import signature, Signature, Parameter
51915165
self.assertEqual(
@@ -5326,6 +5300,10 @@ class MiscTestCase(unittest.TestCase):
53265300
def test__all__(self):
53275301
support.check__all__(self, enum, not_exported={'bin', 'show_flag_values'})
53285302

5303+
@cpython_only
5304+
def test_lazy_import(self):
5305+
ensure_lazy_imports("enum", {"functools", "warnings", "inspect", "re"})
5306+
53295307
def test_doc_1(self):
53305308
class Single(Enum):
53315309
ONE = 1

0 commit comments

Comments
 (0)