[Python-checkins] bpo-43945: [Enum] Deprecate non-standard mixin format() behavior (GH-25649)
ethanfurman
webhook-mailer at python.org
Tue Apr 27 01:43:09 EDT 2021
https://github.com/python/cpython/commit/5987b8c463892e0ab7a63cdae92f34b5eb79732d
commit: 5987b8c463892e0ab7a63cdae92f34b5eb79732d
branch: master
author: Ethan Furman <ethan at stoneleaf.us>
committer: ethanfurman <ethan at stoneleaf.us>
date: 2021-04-26T22:42:57-07:00
summary:
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.
files:
A Misc/NEWS.d/next/Library/2021-04-26-20-52-16.bpo-43945.NgERXO.rst
M Lib/enum.py
M Lib/test/test_enum.py
diff --git a/Lib/enum.py b/Lib/enum.py
index ca6aff6f82512d..bcf411c6b6550c 100644
--- a/Lib/enum.py
+++ b/Lib/enum.py
@@ -1005,6 +1005,14 @@ def __format__(self, format_spec):
val = str(self)
# mix-in branch
else:
+ import warnings
+ warnings.warn(
+ "in 3.12 format() will use the enum member, not the enum member's value;\n"
+ "use a format specifier, such as :d for an IntEnum member, to maintain"
+ "the current display",
+ DeprecationWarning,
+ stacklevel=2,
+ )
cls = self._member_type_
val = self._value_
return cls.__format__(val, format_spec)
diff --git a/Lib/test/test_enum.py b/Lib/test/test_enum.py
index 4f28b80293d352..983c54b8711991 100644
--- a/Lib/test/test_enum.py
+++ b/Lib/test/test_enum.py
@@ -528,6 +528,14 @@ def __format__(self, spec):
self.assertEqual(str(TestFloat.one), 'one')
self.assertEqual('{}'.format(TestFloat.one), 'TestFloat success!')
+ @unittest.skipUnless(
+ sys.version_info[:2] < (3, 12),
+ 'mixin-format now uses member instead of member.value',
+ )
+ def test_mixin_format_warning(self):
+ with self.assertWarns(DeprecationWarning):
+ self.assertEqual(f'{self.Grades.B}', '4')
+
def assertFormatIsValue(self, spec, member):
self.assertEqual(spec.format(member), spec.format(member.value))
diff --git a/Misc/NEWS.d/next/Library/2021-04-26-20-52-16.bpo-43945.NgERXO.rst b/Misc/NEWS.d/next/Library/2021-04-26-20-52-16.bpo-43945.NgERXO.rst
new file mode 100644
index 00000000000000..c01c200caa7801
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2021-04-26-20-52-16.bpo-43945.NgERXO.rst
@@ -0,0 +1,2 @@
+[Enum] Deprecate non-standard mixin format() behavior: in 3.12 the enum
+member, not the member's value, will be used for format() calls.
More information about the Python-checkins
mailing list