Skip to content

gh-145858: Remove DELETE_DEREF bytecode instruction - #148185

Open
Siyet wants to merge 6 commits into
python:mainfrom
Siyet:gh-145858-remove-delete-deref
Open

Siyet wants to merge 6 commits into
python:mainfrom
Siyet:gh-145858-remove-delete-deref

Conversation

@Siyet

@Siyet Siyet commented Apr 6, 2026 •

Copy link
Copy Markdown

Summary

Remove the DELETE_DEREF opcode. The compiler now emits PUSH_NULL +
STORE_DEREF for del of a closure variable, like the DELETE_NAME,
DELETE_GLOBAL and DELETE_ATTR removals. STORE_DEREF with NULL clears
the cell with PyCell_SwapTakeRef and raises if it was already empty, so the
deletion stays atomic on the free-threaded build.

This frees up one opcode slot.

Changes

  • Python/codegen.c: codegen_nameop() now emits PUSH_NULL +
    STORE_DEREF instead of DELETE_DEREF for Del context on deref variables
  • Python/bytecodes.c: Remove DELETE_DEREF instruction definition;
    STORE_DEREF with a NULL stackref clears the cell and raises if it was
    already empty
  • Python/flowgraph.c: Remove DELETE_DEREF from offset fixup switch
  • Doc/library/dis.rst: Remove opcode documentation
  • Doc/whatsnew/3.16.rst: Add a "CPython bytecode changes" entry
  • Include/internal/pycore_magic_number.h: Bump PYC_MAGIC_NUMBER 3708 → 3709
  • Lib/test/test_compiler_codegen.py: Add a codegen test for del of a
    closure variable
  • All generated files regenerated

Test plan

The test plan, the stress and benchmark scripts and their results below are
from the earlier LOAD_DEREF + POP_TOP + PUSH_NULL + STORE_DEREF
version of this PR.

  • test_scope, test_dis, test_compile, test_compiler_assemble,
    test_peepholer, test_opcodes: all pass
  • 14 test modules (1465 tests): all pass on free-threading build
  • Custom stress tests (100K iterations): basic del, reassign after del,
    refcount/leak detection, nested closures, 8-thread concurrent del
  • Benchmark: stable (stdev < 1%)

Stress test script

stress_delete_deref.py
"""
Stress test for DELETE_DEREF removal.
Tests that del on closure variables works correctly with the new
LOAD_DEREF + POP_TOP + PUSH_NULL + STORE_DEREF sequence.
"""
import sys
import threading
import timeit
import statistics
import gc
import weakref

ITERATIONS = 100_000

def test_basic_del_deref():
    """Basic: del a closure variable and verify UnboundLocalError."""
    errors = 0
    for _ in range(ITERATIONS):
        x = 42
        def inner():
            return x
        del x
        try:
            inner()
            errors += 1
        except NameError:
            pass
    assert errors == 0, f"Expected NameError but got value {errors} times"

def test_del_deref_with_reassign():
    """Del then reassign closure variable."""
    for _ in range(ITERATIONS):
        x = "hello"
        def inner():
            return x
        del x
        try:
            inner()
            assert False, "Should have raised"
        except NameError:
            pass
        x = "world"
        assert inner() == "world"

def test_del_deref_refcount():
    """Verify that del properly releases the object (no leaks)."""
    destroyed = [0]
    class Tracer:
        def __del__(self):
            destroyed[0] += 1

    for _ in range(ITERATIONS):
        obj = Tracer()
        ref = weakref.ref(obj)
        def inner():
            return obj
        del obj
        gc.collect()
        assert ref() is None, "Object was not released after del"

    assert destroyed[0] == ITERATIONS, f"Leak detected: only {destroyed[0]}/{ITERATIONS} destroyed"

def test_del_deref_nested():
    """Nested closures with del."""
    for _ in range(ITERATIONS // 10):
        x = [1, 2, 3]
        def level1():
            def level2():
                return x
            return level2
        fn = level1()
        assert fn() == [1, 2, 3]
        del x
        try:
            fn()
            assert False
        except NameError:
            pass

def test_del_deref_threaded():
    """Concurrent del on closure variables."""
    errors = []
    def worker(thread_id):
        try:
            for _ in range(ITERATIONS // 10):
                val = thread_id
                def capture():
                    return val
                assert capture() == thread_id
                del val
                try:
                    capture()
                    errors.append(f"Thread {thread_id}: expected NameError")
                except NameError:
                    pass
        except Exception as exc:
            errors.append(f"Thread {thread_id}: {exc}")

    threads = [threading.Thread(target=worker, args=(tid,)) for tid in range(8)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    assert not errors, f"Thread errors: {errors}"

def test_del_deref_in_loop():
    """Del in a tight loop to stress the new instruction sequence."""
    for _ in range(ITERATIONS):
        values = []
        x = 99
        def reader():
            return x
        values.append(reader())
        del x
        try:
            reader()
        except NameError:
            values.append("deleted")
        x = 100
        values.append(reader())
        assert values == [99, "deleted", 100]

if __name__ == "__main__":
    tests = [
        ("basic_del_deref", test_basic_del_deref),
        ("del_deref_with_reassign", test_del_deref_with_reassign),
        ("del_deref_refcount", test_del_deref_refcount),
        ("del_deref_nested", test_del_deref_nested),
        ("del_deref_threaded", test_del_deref_threaded),
        ("del_deref_in_loop", test_del_deref_in_loop),
    ]

    print(f"Python {sys.version}")
    print(f"Running stress tests ({ITERATIONS} iterations each)...\n")

    failed = 0
    for name, test_fn in tests:
        try:
            test_fn()
            print(f"  PASS: {name}")
        except Exception as exc:
            print(f"  FAIL: {name} -- {exc}")
            failed += 1

    print(f"\nResults: {len(tests) - failed}/{len(tests)} passed")
    if failed:
        sys.exit(1)
    else:
        print("All stress tests PASSED")

Benchmark script

bench_delete_deref.py
"""Benchmark for del on closure variables."""
import timeit
import statistics

ITERATIONS = 100_000

setup = """
def make():
    x = 42
    def inner():
        return x
    del x
    try:
        inner()
    except NameError:
        pass
"""

times = timeit.repeat("make()", setup=setup, number=ITERATIONS, repeat=50)
mean = statistics.mean(times)
stdev = statistics.stdev(times)
print(f"del closure var ({ITERATIONS} iters x 50 rounds):")
print(f"  mean:  {mean:.4f}s")
print(f"  stdev: {stdev:.4f}s")
print(f"  min:   {min(times):.4f}s")
print(f"  max:   {max(times):.4f}s")

Results (free-threading debug build, dedicated server, taskset -c 0)

Stress tests: 6/6 PASSED
Benchmark: 0.4066s ± 0.0036s (min=0.4000, max=0.4144)

📚 Documentation preview 📚: https://cpython-previews--148185.org.readthedocs.build/

Replace DELETE_DEREF with the sequence LOAD_DEREF + POP_TOP + PUSH_NULL + STORE_DEREF in the compiler. Adapt STORE_DEREF to handle NULL stackref for cell clearing.
@bedevere-app

bedevere-app Bot commented Apr 6, 2026

Copy link
Copy Markdown

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

Comment thread Doc/tools/removed-ids.txt Resolved
@github-actions

github-actions Bot commented May 9, 2026

Copy link
Copy Markdown

This PR is stale because it has been open for 30 days with no activity.

@github-actions github-actions Bot added the stale Stale PR or inactive for long period of time. label May 9, 2026
@hugovk
hugovk removed their request for review May 11, 2026 04:58
@github-actions github-actions Bot removed the stale Stale PR or inactive for long period of time. label May 18, 2026
@markshannon

Copy link
Copy Markdown
Member

This looks good. Thanks for doing this, and sorry for leaving it hanging for so long.
Could you fix up the merge conflicts? Then I can merge it

@markshannon

Copy link
Copy Markdown
Member

@Siyet?

@github-actions

github-actions Bot commented Oct 4, 2026

Copy link
Copy Markdown

This PR is stale because it has been open for 90 days with no activity.

@github-actions github-actions Bot added the stale Stale PR or inactive for long period of time. label Oct 4, 2026
Compile `del` of a closure variable as PUSH_NULL + STORE_DEREF, like the
DELETE_NAME, DELETE_GLOBAL and DELETE_ATTR removals. STORE_DEREF with NULL
clears the cell with PyCell_SwapTakeRef and raises if it was already
empty, as DELETE_DEREF did. With LOAD_DEREF + POP_TOP before the store,
two threads of the free-threaded build could both delete the same value.

Also move the What's New entry to 3.16 and add a codegen test.
@Siyet
Siyet requested a review from Eclips4 as a code owner November 24, 2026 18:56
@python-cla-bot

Copy link
Copy Markdown

The following commit authors need to sign the Contributor License Agreement:

CLA not signed

@bedevere-app bedevere-app Bot added the type-feature A feature request or enhancement label Nov 24, 2026
@Siyet

Siyet commented Nov 24, 2026

Copy link
Copy Markdown
Author

Sorry for the long delay. I merged main and resolved the conflicts (magic number 3709, What's New entry moved to 3.16).

I also found that LOAD_DEREF, POP_TOP, PUSH_NULL, STORE_DEREF, the sequence suggested in the issue, makes del of a cell non-atomic on the free-threaded build: two threads can both load the same value and both succeed in deleting it. So I switched to the approach of the DELETE_NAME, DELETE_GLOBAL and DELETE_ATTR removals: del compiles to PUSH_NULL, STORE_DEREF, and STORE_DEREF with NULL clears the cell with PyCell_SwapTakeRef and raises if it was already empty, as DELETE_DEREF did. There is also a new codegen test, like the ones for the DELETE_NAME and DELETE_GLOBAL removals.

@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #36140316 | 📁 Comparing 3715c0e against main (4743be9)

  🔍 Preview build  

3 files changed
± library/dis.html
± whatsnew/3.16.html
± whatsnew/changelog.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting review stale Stale PR or inactive for long period of time. type-feature A feature request or enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants