From ec15a826ce6a49e4b1ba184517da9b739cb3db8f Mon Sep 17 00:00:00 2001 From: Ethan Furman Date: Sat, 31 Aug 2013 19:17:41 -0700 Subject: Close #18738: Route __format__ calls to mixed-in type for mixed Enums (such as IntEnum). --- Lib/enum.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) (limited to 'Lib/enum.py') diff --git a/Lib/enum.py b/Lib/enum.py index 5722b5f7eb1..8219005bb61 100644 --- a/Lib/enum.py +++ b/Lib/enum.py @@ -50,7 +50,6 @@ def _make_class_unpicklable(cls): cls.__reduce__ = _break_on_call_reduce cls.__module__ = '' - class _EnumDict(dict): """Keeps track of definition order of the enum items. @@ -182,7 +181,7 @@ class EnumMeta(type): # double check that repr and friends are not the mixin's or various # things break (such as pickle) - for name in ('__repr__', '__str__', '__getnewargs__'): + for name in ('__repr__', '__str__', '__format__', '__getnewargs__'): class_method = getattr(enum_class, name) obj_method = getattr(member_type, name, None) enum_method = getattr(first_enum, name, None) @@ -441,6 +440,21 @@ class Enum(metaclass=EnumMeta): return self is other return NotImplemented + def __format__(self, format_spec): + # mixed-in Enums should use the mixed-in type's __format__, otherwise + # we can get strange results with the Enum name showing up instead of + # the value + + # pure Enum branch + if self._member_type_ is object: + cls = str + val = str(self) + # mix-in branch + else: + cls = self._member_type_ + val = self.value + return cls.__format__(val, format_spec) + def __getnewargs__(self): return (self._value_, ) -- cgit v1.2.3