任何人都可以解释一下这些python字典,列表变量存储在内存中。我知道在python内存管理是使用堆和堆栈完成的。但是我真的找不到关于在创建字典变量时如何分配内存的简单解释,它是在堆栈框架还是堆空间中创建的?
答案 0 :(得分:3)
好吧,让我们看一下源代码吧!
来自:https://github.com/python/cpython/blob/master/Objects/dictobject.c
static PyObject *
new_dict(PyDictKeysObject *keys, PyObject **values)
{
PyDictObject *mp;
...
mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
...
return (PyObject *)mp;
}
因此,似乎使用dict
PyObject_GC_New()
对象
来自:https://github.com/python/cpython/blob/master/Doc/c-api/gcsupport.rst#id9
.. c:function:: TYPE* PyObject_GC_New(TYPE, PyTypeObject *type)
Analogous to :c:func:`PyObject_New` but for container objects with the
:const:`Py_TPFLAGS_HAVE_GC` flag set.
来自:https://github.com/python/cpython/blob/master/Objects/object.c
PyObject *
_PyObject_New(PyTypeObject *tp)
{
PyObject *op;
op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
if (op == NULL)
return PyErr_NoMemory();
return PyObject_INIT(op, tp);
}
来自:https://github.com/python/cpython/blob/master/Objects/obmalloc.c
#define MALLOC_ALLOC {NULL, _PyMem_RawMalloc, _PyMem_RawCalloc, _PyMem_RawRealloc, _PyMem_RawFree}
#ifdef WITH_PYMALLOC
# define PYMALLOC_ALLOC {NULL, _PyObject_Malloc, _PyObject_Calloc, _PyObject_Realloc, _PyObject_Free}
#endif
#define PYRAW_ALLOC MALLOC_ALLOC
#ifdef WITH_PYMALLOC
# define PYOBJ_ALLOC PYMALLOC_ALLOC
#else
# define PYOBJ_ALLOC MALLOC_ALLOC
static PyMemAllocatorEx _PyObject = PYOBJ_ALLOC;
...
void *
PyObject_Malloc(size_t size)
{
/* see PyMem_RawMalloc() */
if (size > (size_t)PY_SSIZE_T_MAX)
return NULL;
return _PyObject.malloc(_PyObject.ctx, size);
}
我认为现在可以安全地假设这些会调用malloc
,calloc
,realloc
和free
。
此时,这不再是一个python问题,但答案是操作系统依赖于malloc
是在堆栈还是堆上分配。