Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

gh-97933: inline list/dict/set comprehensions #101441

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 56 commits into from
May 9, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
72afa83
gh-97933: inline sync list/dict/set comprehensions
carljm Jan 30, 2023
8988234
simplify cell handling code slightly
carljm Jan 31, 2023
22c4a86
clarify comments
carljm Jan 31, 2023
c1b54f0
enable inlining async comprehensions also
carljm Jan 31, 2023
43db9b8
fix typo
carljm Jan 31, 2023
ed3209b
Merge branch 'main' into inlinecomp2
carljm Jan 31, 2023
aceb6c7
fix outer-cell, inner-local case
carljm Jan 31, 2023
e57c354
fix restoring NULL (unbound outer name) followed by load
carljm Jan 31, 2023
795d854
emit 1 x SWAP N+1 instead of N x SWAP 2
carljm Jan 31, 2023
686221a
remove stray dis.dis() call
carljm Jan 31, 2023
ac99697
fix compiler warning about Py_ssize_t -> int conversion
carljm Jan 31, 2023
db208d5
Merge branch 'main' into inlinecomp2
carljm Jan 31, 2023
8b76051
Merge branch 'main' into inlinecomp2
carljm Feb 1, 2023
4620856
add a couple more tests
carljm Feb 1, 2023
8773653
clear comp locals on entry, eval iter expr first
carljm Feb 1, 2023
be3becc
Merge branch 'main' into inlinecomp2
carljm Feb 9, 2023
f0c051e
fix double decref in error case
carljm Feb 9, 2023
142859a
adjust to RETURN_CONST
carljm Feb 9, 2023
568a470
fix up refcounting
carljm Feb 10, 2023
add772e
Merge branch 'main' into inlinecomp2
carljm Feb 10, 2023
17d5d84
improve importlib comment
carljm Feb 10, 2023
b87d209
mark STORE_FAST_MAYBE_NULL as possibly NULLing a local
carljm Feb 10, 2023
36b2917
Merge branch 'main' into inlinecomp2
carljm Feb 10, 2023
ae0bd02
Merge branch 'main' into inlinecomp2
carljm Feb 13, 2023
9f0fc5b
Merge branch 'main' into inlinecomp2
carljm Feb 20, 2023
463c740
add test for NameError/UnboundLocalError
carljm Feb 28, 2023
67f50ba
fix case where iter var is free in outer scope
carljm Feb 28, 2023
73dc0ed
Merge branch 'main' into inlinecomp2
carljm Feb 28, 2023
ecb313c
Merge branch 'main' into inlinecomp2
carljm Mar 6, 2023
4109baa
add inlining of non-function-scope comprehensions
carljm Mar 7, 2023
d8802a1
simplify scope handling
carljm Mar 7, 2023
1c019a7
Merge branch 'main' into inlinecomp2
carljm Mar 7, 2023
24a9d9f
Merge branch 'main' into inlinecomp2
carljm Mar 8, 2023
b6a025b
add tests for comprehensions in class scope
carljm Mar 8, 2023
90b34de
run all listcomp scope tests in module, class, and func scope
carljm Mar 8, 2023
06db319
Merge branch 'main' into inlinecomp2
carljm Mar 8, 2023
b52046b
handle frame locals materialization in class/module scope
carljm Mar 14, 2023
6c5f269
Merge branch 'main' into inlinecomp2
carljm Mar 14, 2023
1a8f4a0
Merge branch 'main' into inlinecomp2
carljm Mar 17, 2023
1274e2b
Merge branch 'main' into inlinecomp2
carljm May 1, 2023
0727d6f
Merge branch 'main' into inlinecomp2
carljm May 2, 2023
51a1294
update comment
carljm May 2, 2023
8a78a36
Merge branch 'main' into inlinecomp2
carljm May 5, 2023
43722b4
review comments
carljm May 5, 2023
bf9e1f1
fix single backticks
carljm May 5, 2023
ca636a5
better nested test
carljm May 5, 2023
46c7a4f
fix u_fasthidden in nested case
carljm May 5, 2023
fb9f89e
fix refleak
carljm May 5, 2023
baacf5f
Merge branch 'main' into inlinecomp2
carljm May 5, 2023
5914d77
remove assumption that class scopes can't have cellvars
carljm May 5, 2023
ffae4e6
Apply suggestions from code review
carljm May 9, 2023
76077cd
Merge branch 'main' into inlinecomp2
carljm May 9, 2023
a8425a6
review comments
carljm May 9, 2023
656e46b
Apply suggestions from code review
carljm May 9, 2023
1402e7a
Apply suggestions from code review
carljm May 9, 2023
95401fe
Merge branch 'main' into inlinecomp2
carljm May 9, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
review comments
  • Loading branch information
carljm committed May 5, 2023
commit 43722b4aadcdddde1b09cba8161dffdd78f8e5fa
24 changes: 24 additions & 0 deletions 24 Doc/whatsnew/3.12.rst
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,30 @@ New Features
In Python 3.14, the default will switch to ``'data'``.
(Contributed by Petr Viktorin in :pep:`706`.)

.. _whatsnew312-pep709:

PEP 709: Comprehension inlining
-------------------------------

Dictionary, list, and set comprehensions are now inlined, rather than creating a
new single-use function object for each execution of the comprehension. This
speeds up execution of a comprehension by up to 2x.

Comprehension iteration variables remain isolated; they don't overwrite a
variable of the same name in the outer scope, nor are they visible after the
comprehension. This isolation is now maintained via stack/locals manipulation,
not via separate function scope.

Inlining does result in a few visible behavior changes:

* There is no longer a separate frame for the comprehension in tracebacks,
and tracing/profiling no longer shows the comprehension as a function call.
* Calling :func:`locals` inside a comprehension now includes variables
from outside the comprehension, and no longer includes the synthetic `.0`
variable for the comprehension "argument".

Contributed by Carl Meyer and Vladimir Matveev in :pep:`709`.

PEP 688: Making the buffer protocol accessible in Python
--------------------------------------------------------

Expand Down
48 changes: 32 additions & 16 deletions 48 Lib/test/test_listcomps.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@


class ListComprehensionTest(unittest.TestCase):
def _check_in_scopes(self, code, outputs, ns=None, scopes=None):
def _check_in_scopes(self, code, outputs=None, ns=None, scopes=None, raises=()):
code = textwrap.dedent(code)
scopes = scopes or ["module", "class", "function"]
for scope in scopes:
Expand All @@ -118,9 +118,14 @@ def get_output(moddict, name):
def get_output(moddict, name):
return moddict[name]
ns = ns or {}
exec(newcode, ns)
for k, v in outputs.items():
self.assertEqual(get_output(ns, k), v)
try:
exec(newcode, ns)
except raises as e:
# We care about e.g. NameError vs UnboundLocalError
self.assertIs(type(e), raises)
else:
for k, v in (outputs or {}).items():
self.assertEqual(get_output(ns, k), v)

def test_lambdas_with_iteration_var_as_default(self):
code = """
Expand Down Expand Up @@ -236,6 +241,29 @@ def test_introspecting_frame_locals(self):
outputs = {"i": 20}
self._check_in_scopes(code, outputs)

def test_nested(self):
code = """
l = [1, 2, 3]
y = [x*2 for x in [x for x in l]]
carljm marked this conversation as resolved.
Show resolved Hide resolved
"""
outputs = {"y": [2, 4, 6]}
self._check_in_scopes(code, outputs)

def test_nameerror(self):
code = """
[x for x in [1]]
x
"""

self._check_in_scopes(code, raises=NameError)

def test_dunder_name(self):
code = """
y = [__x for __x in [1]]
"""
outputs = {"y": [1]}
self._check_in_scopes(code, outputs)

def test_unbound_local_after_comprehension(self):
def f():
if False:
Expand All @@ -246,18 +274,6 @@ def f():
with self.assertRaises(UnboundLocalError):
f()

def test_nameerror(self):
def f():
[x for x in [1]]
return x

with self.assertRaises(NameError) as ctx:
f()

# UnboundLocalError is a subtype of NameError; in this case we want to
# check that it is actually NameError
self.assertIs(type(ctx.exception), NameError)

def test_unbound_local_inside_comprehension(self):
def f():
l = [None]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
Inline list, dict and set comprehensions to improve performance
:pep:`709`: inline list, dict and set comprehensions to improve performance
and reduce bytecode size.
10 changes: 6 additions & 4 deletions 10 Python/compile.c
Original file line number Diff line number Diff line change
Expand Up @@ -5011,7 +5011,9 @@ push_inlined_comprehension_state(struct compiler *c, location loc,
if (symbol & DEF_LOCAL && ~symbol & DEF_NONLOCAL) {
carljm marked this conversation as resolved.
Show resolved Hide resolved
if (c->u->u_ste->ste_type != FunctionBlock) {
// non-function scope: override this name to use fast locals
PyDict_SetItem(c->u->u_metadata.u_fasthidden, k, Py_True);
if (PyDict_SetItem(c->u->u_metadata.u_fasthidden, k, Py_True) < 0) {
return ERROR;
}
}
long scope = (symbol >> SCOPE_OFFSET) & SCOPE_MASK;
PyObject *outv = PyDict_GetItemWithError(c->u->u_ste->ste_symbols, k);
Expand All @@ -5034,11 +5036,11 @@ push_inlined_comprehension_state(struct compiler *c, location loc,
// the outer version; we'll restore it after running the
// comprehension
Py_INCREF(outv);
if (PyDict_SetItem(c->u->u_ste->ste_symbols, k, v)) {
if (PyDict_SetItem(c->u->u_ste->ste_symbols, k, v) < 0) {
Py_DECREF(outv);
return ERROR;
}
if (PyDict_SetItem(state->temp_symbols, k, outv)) {
if (PyDict_SetItem(state->temp_symbols, k, outv) < 0) {
Py_DECREF(outv);
return ERROR;
}
Expand All @@ -5061,7 +5063,7 @@ push_inlined_comprehension_state(struct compiler *c, location loc,
if (scope == CELL) {
ADDOP_NAME(c, loc, MAKE_CELL, k, cellvars);
}
if (PyList_Append(state->pushed_locals, k)) {
if (PyList_Append(state->pushed_locals, k) < 0) {
return ERROR;
}
}
Expand Down
Morty Proxy This is a proxified and sanitized view of the page, visit original site.