Skip to content

_PyEvalFramePushAndInit_Ex leaks locals on failure if not using fast locals #163172

Backlog

Description

@t-0

Bug report

CALL_FUNCTION_EX passes a new reference to a function globals as locals when not using fast locals. Each failing call will leak a reference, e.g. should _PyStack_UnpackDict() fails because **kwargs is not a string.

diff --git a/Python/ceval.c b/Python/ceval.c
index 446e6a8be4d..e616641ea4d 100644
--- a/Python/ceval.c
+++ b/Python/ceval.c
@@ -2183,6 +2183,7 @@ _PyEvalFramePushAndInit_Ex(PyThreadState *tstate, _PyStackRef func,
     Py_XDECREF(kwargs);
     return new_frame;
 error:
+    Py_XDECREF(locals);
     Py_DECREF(callargs);
     Py_XDECREF(kwargs);

Reproduce with:

import sys, types
g = {}
f = types.FunctionType(compile("pass", "<s>", "exec"), g)
def opt():
    pass
for name, fn in [("non-optimized", f), ("optimized", opt)]:
    t1 = g if fn is f else opt.__globals__
    t0 = sys.getrefcount(t1)
    for _ in range(10):
        try:
            fn(**{1: 2})
        except TypeError:
            pass
    print(name, "globals refcount delta:", sys.getrefcount(t1) - t0)

CPython versions tested on:

3.16, CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

  1. added
    type-bug
    on Dec 4, 2026
  2. added
    interpreter-core
    on Dec 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coretype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions