CPython3.6中函数参数的引用计数 [英] Reference count of function arguments in CPython 3.6

查看:25
本文介绍了CPython3.6中函数参数的引用计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了查明传递给函数的参数是"临时的"(仅传递到函数中)还是在外部引用的,我使用Py_REFCNT。这是在一个C扩展包中完成的,但为了更容易重现,我决定在这里提供一个基于IPython Magic的Cython实现。

在CPython3.5和CPython3.6之间,接受多个参数的函数似乎有些变化(对于只接受一个参数的函数,它仍然可以正常工作):

In [1]: %load_ext cython

In [2]: %%cython
   ...: cdef extern from "Python.h":
   ...:     Py_ssize_t Py_REFCNT(object o)
   ...:
   ...: cpdef func(o, p):
   ...:     return Py_REFCNT(o)

当我在3.5上运行代码时,它会给出预期的结果:

>>> import numpy as np
>>> func(np.ones(3), np.ones(3))
1

但在3.6版本中,它为我提供了2

>>> import numpy as np
>>> func(np.ones(3), np.ones(3))
2

在评论中,有人问我关于C代码的问题,所以是这样的:

static PyObject *
GetRefCount(PyObject *m, PyObject *args) {
    if (PyTuple_CheckExact(args) && PyTuple_Size(args) > 0) {
        Py_ssize_t reference_count = Py_REFCNT(PyTuple_GET_ITEM(args, 0));
        return PyLong_FromSsize_t(reference_count);
    }
    PyErr_SetString(PyExc_TypeError, "wrong input");
    return NULL;
}

和方法定义:

    {"getrefcount",                                     /* ml_name */
     (PyCFunction)GetRefCount,                          /* ml_meth */
     METH_VARARGS,                                      /* ml_flags */
     ""                                                 /* ml_doc */
     },

结果相同:

>>> import numpy as np
>>> getrefcount(np.ones(3))  # 3.5
1
>>> getrefcount(np.ones(3))  # 3.6
2

我想知道在3.6中引用计数在哪里(以及为什么)递增。我已经翻阅了CPython源代码/Python问题跟踪器,但找不到答案。

推荐答案

在Python3.5上,当您的函数执行时,参数恰好从调用者的堆栈中清除。在Python3.6上,参数碰巧仍然在调用方的堆栈上,也在函数的参数元组中。

在Python3.5上,您的函数调用经过here

    else {
        PyObject *callargs;
        callargs = load_args(pp_stack, na);
        if (callargs != NULL) {
            READ_TIMESTAMP(*pintr0);
            C_TRACE(x, PyCFunction_Call(func,callargs,NULL));
            READ_TIMESTAMP(*pintr1);
            Py_XDECREF(callargs);
        }
        else {
            x = NULL;
        }
    }

它从堆栈中删除参数以构建参数元组:

static PyObject *
load_args(PyObject ***pp_stack, int na)
{
    PyObject *args = PyTuple_New(na);
    PyObject *w;

    if (args == NULL)
        return NULL;
    while (--na >= 0) {
        w = EXT_POP(*pp_stack);
        PyTuple_SET_ITEM(args, na, w);
    }
    return args;
}

在3.6上,您的函数调用通过here

if (PyCFunction_Check(func)) {
    PyThreadState *tstate = PyThreadState_GET();

    PCALL(PCALL_CFUNCTION);

    stack = (*pp_stack) - nargs - nkwargs;
    C_TRACE(x, _PyCFunction_FastCallKeywords(func, stack, nargs, kwnames));
}

通过here

PyObject *
_PyCFunction_FastCallKeywords(PyObject *func, PyObject **stack,
                              Py_ssize_t nargs, PyObject *kwnames)
{
    ...

    result = _PyCFunction_FastCallDict(func, stack, nargs, kwdict);
    Py_XDECREF(kwdict);
    return result;
}

通过here

case METH_VARARGS:
case METH_VARARGS | METH_KEYWORDS:
{
    /* Slow-path: create a temporary tuple */
    ...

    tuple = _PyStack_AsTuple(args, nargs);

    ...
}

通过here

for (i=0; i < nargs; i++) {
    PyObject *item = stack[i];
    Py_INCREF(item);
    PyTuple_SET_ITEM(args, i, item);
}

这会将参数保留在堆栈上,并使用对参数的新引用构建一个元组。

这篇关于CPython3.6中函数参数的引用计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆