Skip to content

Commit 6bd9288

Browse files
authored
bpo-43957: [Enum] Deprecate TypeError from containment checks. (GH-25670)
In 3.12 ``True`` or ``False`` will be returned for all containment checks, with ``True`` being returned if the value is either a member of that enum or one of its members' value.
1 parent 9aea31d commit 6bd9288

File tree

5 files changed

+148
-36
lines changed

5 files changed

+148
-36
lines changed

Doc/library/enum.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,12 @@ Data Types
140140
>>> some_var in Color
141141
True
142142

143+
.. note::
144+
145+
In Python 3.12 it will be possible to check for member values and not
146+
just members; until then, a ``TypeError`` will be raised if a
147+
non-Enum-member is used in a containment check.
148+
143149
.. method:: EnumType.__dir__(cls)
144150

145151
Returns ``['__class__', '__doc__', '__members__', '__module__']`` and the

Lib/enum.py

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,8 @@ def __set_name__(self, enum_class, member_name):
280280
# linear.
281281
enum_class._value2member_map_.setdefault(value, enum_member)
282282
except TypeError:
283-
pass
283+
# keep track of the value in a list so containment checks are quick
284+
enum_class._unhashable_values_.append(value)
284285

285286

286287
class _EnumDict(dict):
@@ -440,6 +441,7 @@ def __new__(metacls, cls, bases, classdict, *, boundary=None, _simple=False, **k
440441
classdict['_member_names_'] = []
441442
classdict['_member_map_'] = {}
442443
classdict['_value2member_map_'] = {}
444+
classdict['_unhashable_values_'] = []
443445
classdict['_member_type_'] = member_type
444446
#
445447
# Flag structures (will be removed if final class is not a Flag
@@ -622,6 +624,13 @@ def __call__(cls, value, names=None, *, module=None, qualname=None, type=None, s
622624

623625
def __contains__(cls, member):
624626
if not isinstance(member, Enum):
627+
import warnings
628+
warnings.warn(
629+
"in 3.12 __contains__ will no longer raise TypeError, but will return True or\n"
630+
"False depending on whether the value is a member or the value of a member",
631+
DeprecationWarning,
632+
stacklevel=2,
633+
)
625634
raise TypeError(
626635
"unsupported operand type(s) for 'in': '%s' and '%s'" % (
627636
type(member).__qualname__, cls.__class__.__qualname__))
@@ -1005,14 +1014,15 @@ def __format__(self, format_spec):
10051014
val = str(self)
10061015
# mix-in branch
10071016
else:
1008-
import warnings
1009-
warnings.warn(
1010-
"in 3.12 format() will use the enum member, not the enum member's value;\n"
1011-
"use a format specifier, such as :d for an IntEnum member, to maintain"
1012-
"the current display",
1013-
DeprecationWarning,
1014-
stacklevel=2,
1015-
)
1017+
if not format_spec or format_spec in ('{}','{:}'):
1018+
import warnings
1019+
warnings.warn(
1020+
"in 3.12 format() will use the enum member, not the enum member's value;\n"
1021+
"use a format specifier, such as :d for an IntEnum member, to maintain"
1022+
"the current display",
1023+
DeprecationWarning,
1024+
stacklevel=2,
1025+
)
10161026
cls = self._member_type_
10171027
val = self._value_
10181028
return cls.__format__(val, format_spec)
@@ -1434,6 +1444,7 @@ def convert_class(cls):
14341444
body['_member_names_'] = member_names = []
14351445
body['_member_map_'] = member_map = {}
14361446
body['_value2member_map_'] = value2member_map = {}
1447+
body['_unhashable_values_'] = []
14371448
body['_member_type_'] = member_type = etype._member_type_
14381449
if issubclass(etype, Flag):
14391450
body['_boundary_'] = boundary or etype._boundary_

Lib/test/test_enum.py

Lines changed: 117 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
from test.support import threading_helper
1717
from datetime import timedelta
1818

19+
python_version = sys.version_info[:2]
20+
1921
def load_tests(loader, tests, ignore):
2022
tests.addTests(doctest.DocTestSuite(enum))
2123
if os.path.exists('Doc/library/enum.rst'):
@@ -352,17 +354,38 @@ class IntLogic(int, Enum):
352354
self.assertTrue(IntLogic.true)
353355
self.assertFalse(IntLogic.false)
354356

355-
def test_contains(self):
357+
@unittest.skipIf(
358+
python_version >= (3, 12),
359+
'__contains__ now returns True/False for all inputs',
360+
)
361+
def test_contains_er(self):
356362
Season = self.Season
357363
self.assertIn(Season.AUTUMN, Season)
358364
with self.assertRaises(TypeError):
359-
3 in Season
365+
with self.assertWarns(DeprecationWarning):
366+
3 in Season
360367
with self.assertRaises(TypeError):
361-
'AUTUMN' in Season
362-
368+
with self.assertWarns(DeprecationWarning):
369+
'AUTUMN' in Season
363370
val = Season(3)
364371
self.assertIn(val, Season)
372+
#
373+
class OtherEnum(Enum):
374+
one = 1; two = 2
375+
self.assertNotIn(OtherEnum.two, Season)
365376

377+
@unittest.skipIf(
378+
python_version < (3, 12),
379+
'__contains__ only works with enum memmbers before 3.12',
380+
)
381+
def test_contains_tf(self):
382+
Season = self.Season
383+
self.assertIn(Season.AUTUMN, Season)
384+
self.assertTrue(3 in Season)
385+
self.assertFalse('AUTUMN' in Season)
386+
val = Season(3)
387+
self.assertIn(val, Season)
388+
#
366389
class OtherEnum(Enum):
367390
one = 1; two = 2
368391
self.assertNotIn(OtherEnum.two, Season)
@@ -528,16 +551,28 @@ def __format__(self, spec):
528551
self.assertEqual(str(TestFloat.one), 'one')
529552
self.assertEqual('{}'.format(TestFloat.one), 'TestFloat success!')
530553

531-
@unittest.skipUnless(
532-
sys.version_info[:2] < (3, 12),
554+
@unittest.skipIf(
555+
python_version < (3, 12),
556+
'mixin-format is still using member.value',
557+
)
558+
def test_mixin_format_warning(self):
559+
with self.assertWarns(DeprecationWarning):
560+
self.assertEqual(f'{self.Grades.B}', 'Grades.B')
561+
562+
@unittest.skipIf(
563+
python_version >= (3, 12),
533564
'mixin-format now uses member instead of member.value',
534565
)
535566
def test_mixin_format_warning(self):
536567
with self.assertWarns(DeprecationWarning):
537568
self.assertEqual(f'{self.Grades.B}', '4')
538569

539570
def assertFormatIsValue(self, spec, member):
540-
self.assertEqual(spec.format(member), spec.format(member.value))
571+
if python_version < (3, 12) and (not spec or spec in ('{}','{:}')):
572+
with self.assertWarns(DeprecationWarning):
573+
self.assertEqual(spec.format(member), spec.format(member.value))
574+
else:
575+
self.assertEqual(spec.format(member), spec.format(member.value))
541576

542577
def test_format_enum_date(self):
543578
Holiday = self.Holiday
@@ -2202,7 +2237,7 @@ def __repr__(self):
22022237
description = 'Bn$', 3
22032238

22042239
@unittest.skipUnless(
2205-
sys.version_info[:2] == (3, 9),
2240+
python_version == (3, 9),
22062241
'private variables are now normal attributes',
22072242
)
22082243
def test_warning_for_private_variables(self):
@@ -2225,7 +2260,7 @@ class Private(Enum):
22252260
self.assertEqual(Private._Private__major_, 'Hoolihan')
22262261

22272262
@unittest.skipUnless(
2228-
sys.version_info[:2] < (3, 12),
2263+
python_version < (3, 12),
22292264
'member-member access now raises an exception',
22302265
)
22312266
def test_warning_for_member_from_member_access(self):
@@ -2237,7 +2272,7 @@ class Di(Enum):
22372272
self.assertIs(Di.NO, nope)
22382273

22392274
@unittest.skipUnless(
2240-
sys.version_info[:2] >= (3, 12),
2275+
python_version >= (3, 12),
22412276
'member-member access currently issues a warning',
22422277
)
22432278
def test_exception_for_member_from_member_access(self):
@@ -2617,19 +2652,41 @@ def test_pickle(self):
26172652
test_pickle_dump_load(self.assertIs, FlagStooges.CURLY|FlagStooges.MOE)
26182653
test_pickle_dump_load(self.assertIs, FlagStooges)
26192654

2620-
def test_contains(self):
2655+
@unittest.skipIf(
2656+
python_version >= (3, 12),
2657+
'__contains__ now returns True/False for all inputs',
2658+
)
2659+
def test_contains_er(self):
26212660
Open = self.Open
26222661
Color = self.Color
26232662
self.assertFalse(Color.BLACK in Open)
26242663
self.assertFalse(Open.RO in Color)
26252664
with self.assertRaises(TypeError):
2626-
'BLACK' in Color
2665+
with self.assertWarns(DeprecationWarning):
2666+
'BLACK' in Color
26272667
with self.assertRaises(TypeError):
2628-
'RO' in Open
2668+
with self.assertWarns(DeprecationWarning):
2669+
'RO' in Open
26292670
with self.assertRaises(TypeError):
2630-
1 in Color
2671+
with self.assertWarns(DeprecationWarning):
2672+
1 in Color
26312673
with self.assertRaises(TypeError):
2632-
1 in Open
2674+
with self.assertWarns(DeprecationWarning):
2675+
1 in Open
2676+
2677+
@unittest.skipIf(
2678+
python_version < (3, 12),
2679+
'__contains__ only works with enum memmbers before 3.12',
2680+
)
2681+
def test_contains_tf(self):
2682+
Open = self.Open
2683+
Color = self.Color
2684+
self.assertFalse(Color.BLACK in Open)
2685+
self.assertFalse(Open.RO in Color)
2686+
self.assertFalse('BLACK' in Color)
2687+
self.assertFalse('RO' in Open)
2688+
self.assertTrue(1 in Color)
2689+
self.assertTrue(1 in Open)
26332690

26342691
def test_member_contains(self):
26352692
Perm = self.Perm
@@ -2954,10 +3011,15 @@ def test_repr(self):
29543011
self.assertEqual(repr(~(Open.WO | Open.CE)), 'Open.RW')
29553012
self.assertEqual(repr(Open(~4)), '-5')
29563013

3014+
@unittest.skipUnless(
3015+
python_version < (3, 12),
3016+
'mixin-format now uses member instead of member.value',
3017+
)
29573018
def test_format(self):
2958-
Perm = self.Perm
2959-
self.assertEqual(format(Perm.R, ''), '4')
2960-
self.assertEqual(format(Perm.R | Perm.X, ''), '5')
3019+
with self.assertWarns(DeprecationWarning):
3020+
Perm = self.Perm
3021+
self.assertEqual(format(Perm.R, ''), '4')
3022+
self.assertEqual(format(Perm.R | Perm.X, ''), '5')
29613023

29623024
def test_or(self):
29633025
Perm = self.Perm
@@ -3189,21 +3251,45 @@ def test_programatic_function_from_empty_tuple(self):
31893251
self.assertEqual(len(lst), len(Thing))
31903252
self.assertEqual(len(Thing), 0, Thing)
31913253

3192-
def test_contains(self):
3254+
@unittest.skipIf(
3255+
python_version >= (3, 12),
3256+
'__contains__ now returns True/False for all inputs',
3257+
)
3258+
def test_contains_er(self):
31933259
Open = self.Open
31943260
Color = self.Color
31953261
self.assertTrue(Color.GREEN in Color)
31963262
self.assertTrue(Open.RW in Open)
31973263
self.assertFalse(Color.GREEN in Open)
31983264
self.assertFalse(Open.RW in Color)
31993265
with self.assertRaises(TypeError):
3200-
'GREEN' in Color
3266+
with self.assertWarns(DeprecationWarning):
3267+
'GREEN' in Color
32013268
with self.assertRaises(TypeError):
3202-
'RW' in Open
3269+
with self.assertWarns(DeprecationWarning):
3270+
'RW' in Open
32033271
with self.assertRaises(TypeError):
3204-
2 in Color
3272+
with self.assertWarns(DeprecationWarning):
3273+
2 in Color
32053274
with self.assertRaises(TypeError):
3206-
2 in Open
3275+
with self.assertWarns(DeprecationWarning):
3276+
2 in Open
3277+
3278+
@unittest.skipIf(
3279+
python_version < (3, 12),
3280+
'__contains__ only works with enum memmbers before 3.12',
3281+
)
3282+
def test_contains_tf(self):
3283+
Open = self.Open
3284+
Color = self.Color
3285+
self.assertTrue(Color.GREEN in Color)
3286+
self.assertTrue(Open.RW in Open)
3287+
self.assertTrue(Color.GREEN in Open)
3288+
self.assertTrue(Open.RW in Color)
3289+
self.assertFalse('GREEN' in Color)
3290+
self.assertFalse('RW' in Open)
3291+
self.assertTrue(2 in Color)
3292+
self.assertTrue(2 in Open)
32073293

32083294
def test_member_contains(self):
32093295
Perm = self.Perm
@@ -3685,7 +3771,7 @@ def test_convert(self):
36853771
if name[0:2] not in ('CO', '__')],
36863772
[], msg='Names other than CONVERT_TEST_* found.')
36873773

3688-
@unittest.skipUnless(sys.version_info[:2] == (3, 8),
3774+
@unittest.skipUnless(python_version == (3, 8),
36893775
'_convert was deprecated in 3.8')
36903776
def test_convert_warn(self):
36913777
with self.assertWarns(DeprecationWarning):
@@ -3694,7 +3780,7 @@ def test_convert_warn(self):
36943780
('test.test_enum', '__main__')[__name__=='__main__'],
36953781
filter=lambda x: x.startswith('CONVERT_TEST_'))
36963782

3697-
@unittest.skipUnless(sys.version_info >= (3, 9),
3783+
@unittest.skipUnless(python_version >= (3, 9),
36983784
'_convert was removed in 3.9')
36993785
def test_convert_raise(self):
37003786
with self.assertRaises(AttributeError):
@@ -3703,6 +3789,10 @@ def test_convert_raise(self):
37033789
('test.test_enum', '__main__')[__name__=='__main__'],
37043790
filter=lambda x: x.startswith('CONVERT_TEST_'))
37053791

3792+
@unittest.skipUnless(
3793+
python_version < (3, 12),
3794+
'mixin-format now uses member instead of member.value',
3795+
)
37063796
def test_convert_repr_and_str(self):
37073797
module = ('test.test_enum', '__main__')[__name__=='__main__']
37083798
test_type = enum.IntEnum._convert_(
@@ -3711,7 +3801,8 @@ def test_convert_repr_and_str(self):
37113801
filter=lambda x: x.startswith('CONVERT_STRING_TEST_'))
37123802
self.assertEqual(repr(test_type.CONVERT_STRING_TEST_NAME_A), '%s.CONVERT_STRING_TEST_NAME_A' % module)
37133803
self.assertEqual(str(test_type.CONVERT_STRING_TEST_NAME_A), 'CONVERT_STRING_TEST_NAME_A')
3714-
self.assertEqual(format(test_type.CONVERT_STRING_TEST_NAME_A), '5')
3804+
with self.assertWarns(DeprecationWarning):
3805+
self.assertEqual(format(test_type.CONVERT_STRING_TEST_NAME_A), '5')
37153806

37163807
# global names for StrEnum._convert_ test
37173808
CONVERT_STR_TEST_2 = 'goodbye'

Lib/test/test_signal.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1323,7 +1323,7 @@ def cycle_handlers():
13231323
# race condition, check it.
13241324
self.assertIsInstance(cm.unraisable.exc_value, OSError)
13251325
self.assertIn(
1326-
f"Signal {signum} ignored due to race condition",
1326+
f"Signal {signum:d} ignored due to race condition",
13271327
str(cm.unraisable.exc_value))
13281328
ignored = True
13291329

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
[Enum] Deprecate ``TypeError`` when non-member is used in a containment
2+
check; In 3.12 ``True`` or ``False`` will be returned instead, and
3+
containment will return ``True`` if the value is either a member of that
4+
enum or one of its members' value.

0 commit comments

Comments
 (0)