Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork33.7k
gh-74929: Implement PEP 667#115153
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Uh oh!
There was an error while loading.Please reload this page.
gh-74929: Implement PEP 667#115153
Changes fromall commits
42d71867eeab1b60e70e71454ce40045274de73bc9ca92393ff886ff9690a2d6e9848ab84b0dfbebff28d846de9d00a7421a4344df720e1264d37722eadbf0cbae1999e7edf8523cb754b83311ae2db7cbf45c02026e15ef42980de693ad05dd045b30ecd4df35c5e35844fb406277f9e1c3f56b672d843e325728dc4664652f641f29e6a3e0ca4fef78156a4503145cdac22c49287ff378aacfFile filter
Filter by extension
Conversations
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.
Uh oh!
There was an error while loading.Please reload this page.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -27,3 +27,9 @@ PyAPI_FUNC(int) _PyFrame_IsEntryFrame(PyFrameObject *frame); | ||
| PyAPI_FUNC(int) PyFrame_FastToLocalsWithError(PyFrameObject *f); | ||
| PyAPI_FUNC(void) PyFrame_FastToLocals(PyFrameObject *); | ||
ncoghlan marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| typedef struct { | ||
| PyObject_HEAD | ||
| PyFrameObject* frame; | ||
| } PyFrameLocalsProxyObject; | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| import copy | ||
| import gc | ||
| import operator | ||
| import re | ||
| @@ -13,7 +14,7 @@ | ||
| _testcapi = None | ||
| from test import support | ||
| from test.support importimport_helper,threading_helper, Py_GIL_DISABLED | ||
| from test.support.script_helper import assert_python_ok | ||
| @@ -198,14 +199,6 @@ def inner(): | ||
| tb = tb.tb_next | ||
| return frames | ||
| def test_clear_locals(self): | ||
| # Test f_locals after clear() (issue #21897) | ||
| f, outer, inner = self.make_frames() | ||
| @@ -217,8 +210,8 @@ def test_clear_locals(self): | ||
| def test_locals_clear_locals(self): | ||
| # Test f_locals before and after clear() (to exercise caching) | ||
| f, outer, inner = self.make_frames() | ||
| self.assertNotEqual(outer.f_locals, {}) | ||
| self.assertNotEqual(inner.f_locals, {}) | ||
| outer.clear() | ||
| inner.clear() | ||
| self.assertEqual(outer.f_locals, {}) | ||
| @@ -269,6 +262,177 @@ def inner(): | ||
| r"^<frame at 0x[0-9a-fA-F]+, file %s, line %d, code inner>$" | ||
| % (file_repr, offset + 5)) | ||
| class TestFrameLocals(unittest.TestCase): | ||
| def test_scope(self): | ||
| class A: | ||
| x = 1 | ||
| sys._getframe().f_locals['x'] = 2 | ||
| sys._getframe().f_locals['y'] = 2 | ||
| self.assertEqual(A.x, 2) | ||
| self.assertEqual(A.y, 2) | ||
| def f(): | ||
| x = 1 | ||
| sys._getframe().f_locals['x'] = 2 | ||
| sys._getframe().f_locals['y'] = 2 | ||
| self.assertEqual(x, 2) | ||
| self.assertEqual(locals()['y'], 2) | ||
| f() | ||
| def test_closure(self): | ||
| x = 1 | ||
| y = 2 | ||
| def f(): | ||
| z = x + y | ||
| d = sys._getframe().f_locals | ||
| self.assertEqual(d['x'], 1) | ||
| self.assertEqual(d['y'], 2) | ||
| d['x'] = 2 | ||
| d['y'] = 3 | ||
| f() | ||
| self.assertEqual(x, 2) | ||
| self.assertEqual(y, 3) | ||
| def test_as_dict(self): | ||
| x = 1 | ||
| y = 2 | ||
| d = sys._getframe().f_locals | ||
| # self, x, y, d | ||
| self.assertEqual(len(d), 4) | ||
| self.assertIs(d['d'], d) | ||
| self.assertEqual(set(d.keys()), set(['x', 'y', 'd', 'self'])) | ||
| self.assertEqual(len(d.values()), 4) | ||
| self.assertIn(1, d.values()) | ||
| self.assertEqual(len(d.items()), 4) | ||
| self.assertIn(('x', 1), d.items()) | ||
| self.assertEqual(d.__getitem__('x'), 1) | ||
| d.__setitem__('x', 2) | ||
| self.assertEqual(d['x'], 2) | ||
| self.assertEqual(d.get('x'), 2) | ||
| self.assertIs(d.get('non_exist', None), None) | ||
| self.assertEqual(d.__len__(), 4) | ||
| self.assertEqual(set([key for key in d]), set(['x', 'y', 'd', 'self'])) | ||
| self.assertIn('x', d) | ||
| self.assertTrue(d.__contains__('x')) | ||
gaogaotiantian marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| self.assertEqual(reversed(d), list(reversed(d.keys()))) | ||
| d.update({'x': 3, 'z': 4}) | ||
| self.assertEqual(d['x'], 3) | ||
| self.assertEqual(d['z'], 4) | ||
| with self.assertRaises(TypeError): | ||
| d.update([1, 2]) | ||
| self.assertEqual(d.setdefault('x', 5), 3) | ||
| self.assertEqual(d.setdefault('new', 5), 5) | ||
| self.assertEqual(d['new'], 5) | ||
| with self.assertRaises(KeyError): | ||
| d['non_exist'] | ||
| def test_as_number(self): | ||
| x = 1 | ||
| y = 2 | ||
| d = sys._getframe().f_locals | ||
| self.assertIn('z', d | {'z': 3}) | ||
| d |= {'z': 3} | ||
| self.assertEqual(d['z'], 3) | ||
| d |= {'y': 3} | ||
| self.assertEqual(d['y'], 3) | ||
| with self.assertRaises(TypeError): | ||
| d |= 3 | ||
| with self.assertRaises(TypeError): | ||
| _ = d | [3] | ||
| def test_non_string_key(self): | ||
| d = sys._getframe().f_locals | ||
| d[1] = 2 | ||
| self.assertEqual(d[1], 2) | ||
| def test_write_with_hidden(self): | ||
| def f(): | ||
| f_locals = [sys._getframe().f_locals for b in [0]][0] | ||
| f_locals['b'] = 2 | ||
| f_locals['c'] = 3 | ||
| self.assertEqual(b, 2) | ||
| self.assertEqual(c, 3) | ||
| b = 0 | ||
| c = 0 | ||
| f() | ||
| def test_repr(self): | ||
| x = 1 | ||
| # Introduce a reference cycle | ||
| frame = sys._getframe() | ||
| self.assertEqual(repr(frame.f_locals), repr(dict(frame.f_locals))) | ||
| def test_delete(self): | ||
| x = 1 | ||
| d = sys._getframe().f_locals | ||
| with self.assertRaises(TypeError): | ||
| del d['x'] | ||
| with self.assertRaises(AttributeError): | ||
| d.clear() | ||
| with self.assertRaises(AttributeError): | ||
| d.pop('x') | ||
| @support.cpython_only | ||
| def test_sizeof(self): | ||
| proxy = sys._getframe().f_locals | ||
| support.check_sizeof(self, proxy, support.calcobjsize("P")) | ||
| def test_unsupport(self): | ||
| x = 1 | ||
| d = sys._getframe().f_locals | ||
| with self.assertRaises(AttributeError): | ||
| d.copy() | ||
| with self.assertRaises(TypeError): | ||
| copy.copy(d) | ||
| with self.assertRaises(TypeError): | ||
| copy.deepcopy(d) | ||
| class TestFrameCApi(unittest.TestCase): | ||
| def test_basic(self): | ||
| x = 1 | ||
| ctypes = import_helper.import_module('ctypes') | ||
| PyEval_GetFrameLocals = ctypes.pythonapi.PyEval_GetFrameLocals | ||
| PyEval_GetFrameLocals.restype = ctypes.py_object | ||
| frame_locals = PyEval_GetFrameLocals() | ||
| self.assertTrue(type(frame_locals), dict) | ||
| self.assertEqual(frame_locals['x'], 1) | ||
| frame_locals['x'] = 2 | ||
| self.assertEqual(x, 1) | ||
| PyEval_GetFrameGlobals = ctypes.pythonapi.PyEval_GetFrameGlobals | ||
| PyEval_GetFrameGlobals.restype = ctypes.py_object | ||
| frame_globals = PyEval_GetFrameGlobals() | ||
| self.assertTrue(type(frame_globals), dict) | ||
gaogaotiantian marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| self.assertIs(frame_globals, globals()) | ||
| PyEval_GetFrameBuiltins = ctypes.pythonapi.PyEval_GetFrameBuiltins | ||
| PyEval_GetFrameBuiltins.restype = ctypes.py_object | ||
| frame_builtins = PyEval_GetFrameBuiltins() | ||
| self.assertEqual(frame_builtins, __builtins__) | ||
| PyFrame_GetLocals = ctypes.pythonapi.PyFrame_GetLocals | ||
| PyFrame_GetLocals.argtypes = [ctypes.py_object] | ||
| PyFrame_GetLocals.restype = ctypes.py_object | ||
| frame = sys._getframe() | ||
| f_locals = PyFrame_GetLocals(frame) | ||
| self.assertTrue(f_locals['x'], 1) | ||
| f_locals['x'] = 2 | ||
| self.assertEqual(x, 2) | ||
| class TestIncompleteFrameAreInvisible(unittest.TestCase): | ||
| def test_issue95818(self): | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -622,9 +622,14 @@ def test_exception_in_post_comp_call(self): | ||
| def test_frame_locals(self): | ||
| code = """ | ||
| val ="a" in[sys._getframe().f_locals for a in [0]][0] | ||
Contributor There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. I think we've changed the intent of the test here. It was previously checking that To cover both aspects, I think we need two test cases (first one shows that deftest_frame_locals_in_listcomp(self):# Iteration variable is accessible via f_locals proxy while the listcomp is runningcode=""" val = [sys._getframe().f_locals["a"] for a in [0]][0] """importsysself._check_in_scopes(code, {"val":0},ns={"sys":sys})deftest_frame_locals_after_listcomp(self):# Iteration variable is no longer accessible via f_locals proxy after listcomp finishescode=""" val = "a" in [sys._getframe().f_locals for a in [0]][0] """importsysself._check_in_scopes(code, {"val":False},ns={"sys":sys}) MemberAuthor There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. That's a very interesting point because it introduced a new issue - should we include the hidden fast local in val= [sys._getframe().f_locals["a"]forain [0]][0] What should the Member There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. Hidden fast-locals were designed to mimic the prior behavior when comprehensions were previously implemented as one-shot functions. So as much as is feasible, the behavior of Member There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. The second proposed test in@ncoghlan 's comment is not correct. Nor is the test as currently modified in the PR. If you access Of course if you access the frame outside the comprehension, the comprehension's hidden fast locals should not be present in its Currently in main, module globals are present in the
I suspect this is also not a problem in practice, though if we can reasonably return a proxy that can support it, it would be even better. Member There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more.
I don't think this is correct. MemberAuthor There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. I think the key here is "as if it's a one-shot function". That's infeasible with the current compiler because it's not a function anymore. For a function, we have a dedicated frame object that keeps the local variables, which can last longer than the intepreter frame as long as there are references on it. In that way, we can always access the variables on that frame even when the actual interpreter frame is gone. However, with inline comprehension, it fakes the "function call" and clear the hidden variable - there's no mechanism currently to prevent the variable from being cleared. If we want this, we'll probably need to change the compiler and the interpreter which will definitely postpone this PEP to 3.14 (and would probably make the compiler code more complicated). MemberAuthor There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. For class and module level comprehensions, can we return a proxy if Member There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more.
It depends whether we are aiming for "correctness" for the actual situation (that the comprehension doesn't have its own frame), or for the backwards-compatible fiction (which PEP 709 only partially maintained, but did jump through hoops to maintain in terms of visibility of class-scoped variables) that comprehensions still behave as if they have their own frame. But as@gaogaotiantian points out, it may be very hard or impossible to maintain that fiction in this case, while still having TBH in the long term I think it would be better to move away from that fiction anyway, but it will have backwards-compatibility implications. Today in I don't know why someone relying on that couldn't just use
Certainly the dict returned when I think returning a proxy inside the module- or class-scoped comprehension is more internally consistent for PEP 667; returning a dict (that includes the comprehension iteration variable) would be a bit more backward-compatible. Member There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. I'm not sure I follow the details, but I agree that people who access | ||
| """ | ||
| import sys | ||
| self._check_in_scopes(code, {"val": False}, ns={"sys": sys}) | ||
| code = """ | ||
| val = [sys._getframe().f_locals["a"] for a in [0]][0] | ||
| """ | ||
| self._check_in_scopes(code, {"val": 0}, ns={"sys": sys}) | ||
| def _recursive_replace(self, maybe_code): | ||
Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.
Uh oh!
There was an error while loading.Please reload this page.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Implement PEP 667 - converted ``frame.f_locals`` to a write through proxy |
Uh oh!
There was an error while loading.Please reload this page.