[Python-checkins] bpo-34750: [Enum] add `_EnumDict.update()` support (GH-23725)

ethanfurman webhook-mailer at python.org
Thu Dec 10 16:07:14 EST 2020


https://github.com/python/cpython/commit/a65828717982e6a56382d7aff738478f5b5b25d0
commit: a65828717982e6a56382d7aff738478f5b5b25d0
branch: master
author: Ethan Furman <ethan at stoneleaf.us>
committer: ethanfurman <ethan at stoneleaf.us>
date: 2020-12-10T13:07:00-08:00
summary:

bpo-34750: [Enum] add `_EnumDict.update()` support (GH-23725)

This allows easier Enum construction in unusual cases, such as including dynamic member definitions into a class definition:

# created dynamically
foo_defines = {'FOO_CAT': 'aloof', 'BAR_DOG': 'friendly', 'FOO_HORSE': 'big'}

class Foo(Enum):
    vars().update({
            k: v
            for k, v in foo_defines.items()
            if k.startswith('FOO_')
            })
    def upper(self):
        # example method
        return self.value.upper()

files:
A Misc/NEWS.d/next/Library/2020-12-09-14-15-48.bpo-34750.x8TASR.rst
M Lib/enum.py
M Lib/test/test_enum.py

diff --git a/Lib/enum.py b/Lib/enum.py
index ed0c9ce72d01c..0070ebe136353 100644
--- a/Lib/enum.py
+++ b/Lib/enum.py
@@ -136,7 +136,7 @@ def __setitem__(self, key, value):
                 key = '_order_'
         elif key in self._member_names:
             # descriptor overwriting an enum?
-            raise TypeError('Attempted to reuse key: %r' % key)
+            raise TypeError('%r already defined as: %r' % (key, self[key]))
         elif key in self._ignore:
             pass
         elif not _is_descriptor(value):
@@ -157,6 +157,16 @@ def __setitem__(self, key, value):
             self._last_values.append(value)
         super().__setitem__(key, value)
 
+    def update(self, members, **more_members):
+        try:
+            for name in members.keys():
+                self[name] = members[name]
+        except AttributeError:
+            for name, value in members:
+                self[name] = value
+        for name, value in more_members.items():
+            self[name] = value
+
 
 # Dummy value for Enum as EnumMeta explicitly checks for it, but of course
 # until EnumMeta finishes running the first time the Enum class doesn't exist.
diff --git a/Lib/test/test_enum.py b/Lib/test/test_enum.py
index f245eb6ccaeee..a83241cbb577a 100644
--- a/Lib/test/test_enum.py
+++ b/Lib/test/test_enum.py
@@ -2186,6 +2186,34 @@ class Strings(StrEnum):
         self.assertEqual([Strings.ONE, Strings.TWO], ['one', 'two'])
 
 
+    def test_dynamic_members_with_static_methods(self):
+        #
+        foo_defines = {'FOO_CAT': 'aloof', 'BAR_DOG': 'friendly', 'FOO_HORSE': 'big'}
+        class Foo(Enum):
+            vars().update({
+                    k: v
+                    for k, v in foo_defines.items()
+                    if k.startswith('FOO_')
+                    })
+            def upper(self):
+                return self.value.upper()
+        self.assertEqual(list(Foo), [Foo.FOO_CAT, Foo.FOO_HORSE])
+        self.assertEqual(Foo.FOO_CAT.value, 'aloof')
+        self.assertEqual(Foo.FOO_HORSE.upper(), 'BIG')
+        #
+        with self.assertRaisesRegex(TypeError, "'FOO_CAT' already defined as: 'aloof'"):
+            class FooBar(Enum):
+                vars().update({
+                        k: v
+                        for k, v in foo_defines.items()
+                        if k.startswith('FOO_')
+                        },
+                        **{'FOO_CAT': 'small'},
+                        )
+                def upper(self):
+                    return self.value.upper()
+
+
 class TestOrder(unittest.TestCase):
 
     def test_same_members(self):
diff --git a/Misc/NEWS.d/next/Library/2020-12-09-14-15-48.bpo-34750.x8TASR.rst b/Misc/NEWS.d/next/Library/2020-12-09-14-15-48.bpo-34750.x8TASR.rst
new file mode 100644
index 0000000000000..c98ba14797af9
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2020-12-09-14-15-48.bpo-34750.x8TASR.rst
@@ -0,0 +1 @@
+[Enum] `_EnumDict.update()` is now supported



More information about the Python-checkins mailing list