summaryrefslogtreecommitdiffstats
path: root/Lib/enum.py
diff options
context:
space:
mode:
authorEthan Furman <ethan@stoneleaf.us>2015-03-19 01:19:30 (GMT)
committerEthan Furman <ethan@stoneleaf.us>2015-03-19 01:19:30 (GMT)
commit482fe0477e5923f0b8fff16c59052650cf7247cf (patch)
tree0b2ee2281894cda0a745373a8a5df9569a33ec55 /Lib/enum.py
parentd833779ceaebeb29352488ffddabf5fc2f070364 (diff)
downloadcpython-482fe0477e5923f0b8fff16c59052650cf7247cf.zip
cpython-482fe0477e5923f0b8fff16c59052650cf7247cf.tar.gz
cpython-482fe0477e5923f0b8fff16c59052650cf7247cf.tar.bz2
issue23673
add private method to enum to support replacing global constants with Enum members: - search for candidate constants via supplied filter - create new enum class and members - insert enum class and replace constants with members via supplied module name - replace __reduce_ex__ with function that returns member name, so previous Python versions can unpickle modify IntEnum classes to use new method
Diffstat (limited to 'Lib/enum.py')
-rw-r--r--Lib/enum.py26
1 files changed, 26 insertions, 0 deletions
diff --git a/Lib/enum.py b/Lib/enum.py
index 9b19c1d..3cd3df8 100644
--- a/Lib/enum.py
+++ b/Lib/enum.py
@@ -511,11 +511,37 @@ class Enum(metaclass=EnumMeta):
"""The value of the Enum member."""
return self._value_
+ @classmethod
+ def _convert(cls, name, module, filter, source=None):
+ """
+ Create a new Enum subclass that replaces a collection of global constants
+ """
+ # convert all constants from source (or module) that pass filter() to
+ # a new Enum called name, and export the enum and its members back to
+ # module;
+ # also, replace the __reduce_ex__ method so unpickling works in
+ # previous Python versions
+ module_globals = vars(sys.modules[module])
+ if source:
+ source = vars(source)
+ else:
+ source = module_globals
+ members = {name: value for name, value in source.items()
+ if filter(name)}
+ cls = cls(name, members, module=module)
+ cls.__reduce_ex__ = _reduce_ex_by_name
+ module_globals.update(cls.__members__)
+ module_globals[name] = cls
+ return cls
+
class IntEnum(int, Enum):
"""Enum where members are also (and must be) ints"""
+def _reduce_ex_by_name(self, proto):
+ return self.name
+
def unique(enumeration):
"""Class decorator for enumerations ensuring unique member values."""
duplicates = []