Close issue20653: allow Enum subclasses to override __reduce_ex__

This commit is contained in:
Ethan Furman 2014-02-18 12:37:12 -08:00
parent e3e786c963
commit dc87052c0c
2 changed files with 73 additions and 14 deletions

View file

@ -116,12 +116,14 @@ class EnumMeta(type):
enum_class._value2member_map_ = {}
# check for a supported pickle protocols, and if not present sabotage
# pickling, since it won't work anyway
if member_type is not object:
methods = ('__getnewargs_ex__', '__getnewargs__',
'__reduce_ex__', '__reduce__')
if not any(map(member_type.__dict__.get, methods)):
_make_class_unpicklable(enum_class)
# pickling, since it won't work anyway.
# if new class implements its own __reduce_ex__, do not sabotage
if classdict.get('__reduce_ex__') is None:
if member_type is not object:
methods = ('__getnewargs_ex__', '__getnewargs__',
'__reduce_ex__', '__reduce__')
if not any(map(member_type.__dict__.get, methods)):
_make_class_unpicklable(enum_class)
# instantiate them, checking for duplicates as we go
# we instantiate first instead of checking for duplicates first in case
@ -167,7 +169,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__', '__format__', '__getnewargs__', '__reduce_ex__'):
for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'):
class_method = getattr(enum_class, name)
obj_method = getattr(member_type, name, None)
enum_method = getattr(first_enum, name, None)
@ -192,8 +194,9 @@ class EnumMeta(type):
(i.e. Color = Enum('Color', names='red green blue')).
When used for the functional API: `module`, if set, will be stored in
the new class' __module__ attribute; `type`, if set, will be mixed in
as the first base class.
the new class' __module__ attribute; `qualname`, if set, will be stored
in the new class' __qualname__ attribute; `type`, if set, will be mixed
in as the first base class.
Note: if `module` is not set this routine will attempt to discover the
calling module by walking the frame stack; if this is unsuccessful
@ -465,14 +468,11 @@ class Enum(metaclass=EnumMeta):
val = self.value
return cls.__format__(val, format_spec)
def __getnewargs__(self):
return (self._value_, )
def __hash__(self):
return hash(self._name_)
def __reduce_ex__(self, proto):
return self.__class__, self.__getnewargs__()
return self.__class__, (self._value_, )
# DynamicClassAttribute is used to provide access to the `name` and
# `value` properties of enum members while keeping some measure of