[Python-checkins] gh-94808: Cover `LOAD_GLOBAL` for custom dict subtypes (GH-96767)

iritkatriel webhook-mailer at python.org
Fri Nov 4 05:58:45 EDT 2022


https://github.com/python/cpython/commit/044bcc1771fe7e2f8eba21793a72ba15e75e6715
commit: 044bcc1771fe7e2f8eba21793a72ba15e75e6715
branch: main
author: Nikita Sobolev <mail at sobolevn.me>
committer: iritkatriel <1055913+iritkatriel at users.noreply.github.com>
date: 2022-11-04T09:58:38Z
summary:

gh-94808: Cover `LOAD_GLOBAL` for custom dict subtypes (GH-96767)

files:
M Lib/test/test_builtin.py

diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
index 31e50638d4a7..814ebe35ae7d 100644
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -736,6 +736,7 @@ def test_exec_globals(self):
         self.assertRaises(TypeError,
                           exec, code, {'__builtins__': 123})
 
+    def test_exec_globals_frozen(self):
         class frozendict_error(Exception):
             pass
 
@@ -767,6 +768,36 @@ def __setitem__(self, key, value):
         self.assertRaises(frozendict_error,
                           exec, code, namespace)
 
+    def test_exec_globals_error_on_get(self):
+        # custom `globals` or `builtins` can raise errors on item access
+        class setonlyerror(Exception):
+            pass
+
+        class setonlydict(dict):
+            def __getitem__(self, key):
+                raise setonlyerror
+
+        # globals' `__getitem__` raises
+        code = compile("globalname", "test", "exec")
+        self.assertRaises(setonlyerror,
+                          exec, code, setonlydict({'globalname': 1}))
+
+        # builtins' `__getitem__` raises
+        code = compile("superglobal", "test", "exec")
+        self.assertRaises(setonlyerror, exec, code,
+                          {'__builtins__': setonlydict({'superglobal': 1})})
+
+    def test_exec_globals_dict_subclass(self):
+        class customdict(dict):  # this one should not do anything fancy
+            pass
+
+        code = compile("superglobal", "test", "exec")
+        # works correctly
+        exec(code, {'__builtins__': customdict({'superglobal': 1})})
+        # custom builtins dict subclass is missing key
+        self.assertRaisesRegex(NameError, "name 'superglobal' is not defined",
+                               exec, code, {'__builtins__': customdict()})
+
     def test_exec_redirected(self):
         savestdout = sys.stdout
         sys.stdout = None # Whatever that cannot flush()



More information about the Python-checkins mailing list