8000 bpo-43945: [Enum] Deprecate non-standard mixin format() behavior (GH-… · python/cpython@5987b8c · GitHub
[go: up one dir, main page]

Skip to content

Commit 5987b8c

Browse files
authored
bpo-43945: [Enum] Deprecate non-standard mixin format() behavior (GH-25649)
In 3.12 the enum member, not the member's value, will be used for format() calls. Format specifiers can be used to retain the current display of enum members: Example enumeration: class Color(IntEnum): RED = 1 GREEN = 2 BLUE = 3 Current behavior: f'{Color.RED}' --> '1' Future behavior: f'{Color.RED}' --> 'RED' Using d specifier: f'{Color.RED:d}' --> '1' Using specifiers can be done now and is future-compatible.
1 parent cfe523b commit 5987b8c

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

Lib/enum.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1005,6 +1005,14 @@ def __format__(self, format_spec):
10051005
val = str(self)
10061006
# mix-in branch
10071007
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+
)
10081016
cls = self._member_type_
10091017
val = self._value_
10101018
return cls.__format__(val, format_spec)

Lib/test/test_enum.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -528,6 +528,14 @@ def __format__(self, spec):
528528
self.assertEqual(str(TestFloat.one), 'one')
529529
self.assertEqual('{}'.format(TestFloat.one), 'TestFloat success!')
530530

531+
@unittest.skipUnless(
532+
sys.version_info[:2] < (3, 12),
533+
'mixin-format now uses member instead of member.value',
534+
)
535+
def test_mixin_format_warning(self):
536+
with self.assertWarns(DeprecationWarning):
537+
self.assertEqual(f'{self.Grades.B}', '4')
538+
531539
def assertFormatIsValue(self, spec, member):
532540
self.assertEqual(spec.format(member), spec.format(member.value))
533541

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[Enum] Deprecate non-standard mixin format() behavior: in 3.12 the enum
2+
member, not the member's value, will be used for format() calls.

0 commit comments

Comments
 (0)
0