Python 整數(shù)對象

整數(shù)對象 PyIntObject

PyIntObject 是一個值不可變對象

定義

typedef struct {
    PyObject_HEAD
    long ob_ival;
} PyIntObject;

相應(yīng)的與整數(shù)類型相對應(yīng)的類型對象為PyInt_Type

PyTypeObject PyInt_Type = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "int",
    sizeof(PyIntObject),
    0,
    (destructor)int_dealloc,                    /* tp_dealloc */
    (printfunc)int_print,                       /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    (cmpfunc)int_compare,                       /* tp_compare */
    (reprfunc)int_to_decimal_string,            /* tp_repr */
    &int_as_number,                             /* tp_as_number */
    0,                                          /* tp_as_sequence */
    0,                                          /* tp_as_mapping */
    (hashfunc)int_hash,                         /* tp_hash */
    0,                                          /* tp_call */
    (reprfunc)int_to_decimal_string,            /* tp_str */
    PyObject_GenericGetAttr,                    /* tp_getattro */
    0,                                          /* tp_setattro */
    0,                                          /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
        Py_TPFLAGS_BASETYPE | Py_TPFLAGS_INT_SUBCLASS,          /* tp_flags */
    int_doc,                                    /* tp_doc */
    0,                                          /* tp_traverse */
    0,                                          /* tp_clear */
    0,                                          /* tp_richcompare */
    0,                                          /* tp_weaklistoffset */
    0,                                          /* tp_iter */
    0,                                          /* tp_iternext */
    int_methods,                                /* tp_methods */
    0,                                          /* tp_members */
    int_getset,                                 /* tp_getset */
    0,                                          /* tp_base */
    0,                                          /* tp_dict */
    0,                                          /* tp_descr_get */
    0,                                          /* tp_descr_set */
    0,                                          /* tp_dictoffset */
    0,                                          /* tp_init */
    0,                                          /* tp_alloc */
    int_new,                                    /* tp_new */
};
Attribute Operation
int_dealloc PyIntObject 對象的析構(gòu)操作
int_free 對象的釋放操作
int_repr 轉(zhuǎn)化為PyStringObject對象
int_hash 獲得hash值
int_print 打印
int_compare 比較
int_as_number 數(shù)值操作集合
int_methods 成員函數(shù)集合

其中含義

Attribute Operation
int_dealloc PyIntObject 對象的析構(gòu)操作
int_free 對象的釋放操作
int_repr 轉(zhuǎn)化為PyStringObject對象
int_hash 獲得hash值
int_print 打印
int_compare 比較
int_as_number 數(shù)值操作集合
int_methods 成員函數(shù)集合

創(chuàng)建與維護

創(chuàng)建

在python的內(nèi)部,python為這些內(nèi)建的對象提供了特定的C API

創(chuàng)建一個PyIntObject 可以由下面三種方式:

    PyObject *PyInt_FromLong(long ival)
    PyObject* PyInt_FromString(char *s, char **pend, int base)
#ifdef Py_USING_UNICODE
    PyObject*PyInt_FromUnicode(Py_UNICODE *s, int length, int base)
#endif

小整數(shù)

由于整數(shù)在程序中非常頻繁的使用,尤其是小整數(shù),那么為了確保效率,便不可能頻繁的申請新內(nèi)存來創(chuàng)建整數(shù)對象,不斷的釋放就內(nèi)存。因此,為提高效率,python對小整數(shù)使用了內(nèi)存池技術(shù)。

[intobject.c]
#ifndef NSMALLPOSINTS
    #define NSMALLPOSINTS           257
#endif
#ifndef NSMALLNEGINTS
    #define NSMALLNEGINTS           5
#endif
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
/* References to small integers are saved in this array so that they
   can be shared.
   The integers that are saved are those in the range
   -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
*/
    static PyIntObject *small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
#endif

(可以通過以上源碼的方式來修改小整數(shù)的范圍)
在上面代碼中還定義了small_ints來作為小整數(shù)的對象池

大整數(shù)

對于大整數(shù),python運行環(huán)境提供了一塊內(nèi)存,來給這些大整數(shù)輪流使用

[intobject.c]
#define BLOCK_SIZE      1000    /* 1K less typical malloc overhead */
#define BHEAD_SIZE      8       /* Enough for a 64-bit pointer */
#define N_INTOBJECTS    ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyIntObject))

struct _intblock {
    struct _intblock *next;
    PyIntObject objects[N_INTOBJECTS];
};

typedef struct _intblock PyIntBlock;

static PyIntBlock *block_list = NULL;
static PyIntObject *free_list = NULL;

(上述代碼顯示了python通過單鏈表的方式來維護這塊內(nèi)存)

添加和刪除

  • 添加,創(chuàng)建PyIntObject對象
[intobject.c]
PyObject *
PyInt_FromLong(long ival)
{
    register PyIntObject *v;
    // 小整數(shù)池是否被激活
#if NSMALLNEGINTS + NSMALLPOSINTS > 0  
    // 判斷是否在小整數(shù)池的范圍內(nèi)
    if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
        // 獲得相應(yīng)值的小整數(shù)對象
        v = small_ints[ival + NSMALLNEGINTS];
        // 引用計數(shù)加一
        Py_INCREF(v);
#ifdef COUNT_ALLOCS
        if (ival >= 0)
            quick_int_allocs++;
        else
            quick_neg_int_allocs++;
#endif
        return (PyObject *) v;
    }
#endif
    //為通用整數(shù)對象池申請新內(nèi)存空間
    //第一次運行時free_list為NULL,(已用完,也會為NULL)
    if (free_list == NULL) {
        if ((free_list = fill_free_list()) == NULL)
            return NULL;
    }
    /* Inline PyObject_New */
    v = free_list;
    free_list = (PyIntObject *)Py_TYPE(v);
    (void)PyObject_INIT(v, &PyInt_Type);
    v->ob_ival = ival;
    return (PyObject *) v;
}

關(guān)于內(nèi)存池的分配fill_free_list

[intobject.c]
static PyIntObject *
fill_free_list(void)
{
    PyIntObject *p, *q;
    /* Python's object allocator isn't appropriate for large blocks. */
    p = (PyIntObject *) PyMem_MALLOC(sizeof(PyIntBlock));
    if (p == NULL)
        return (PyIntObject *) PyErr_NoMemory();
    ((PyIntBlock *)p)->next = block_list;
    block_list = (PyIntBlock *)p;
    /* Link the int objects together, from rear to front, then return
       the address of the last int object in the block. */
    p = &((PyIntBlock *)p)->objects[0];
    q = p + N_INTOBJECTS;
    //連接為鏈表
    while (--q > p)
        Py_TYPE(q) = (struct _typeobject *)(q-1);
    Py_TYPE(q) = NULL;
    return p + N_INTOBJECTS - 1;
}

(注意,這里使用了PyObject中的ob_type指針作為連接指針)

連接為鏈表
  • 刪除,釋放PyIntObject對象
[intobject.c]
static void
int_dealloc(PyIntObject *v)
{
    //檢查對象是否是PyIntObject(避免對其派生類進行內(nèi)存操作)
    if (PyInt_CheckExact(v)) {
        //是PyIntObject類型
        Py_TYPE(v) = (struct _typeobject *)free_list;
        free_list = v;
    }
    else
        //不是PyIntObject類型,是其派生類
        Py_TYPE(v)->tp_free((PyObject *)v);
}

(在釋放時,將釋放掉的對象內(nèi)存加到了free_list鏈表,以備生成時重復(fù)使用)

  • 小整數(shù)對象池的初始化
[intobject.c]
int
_PyInt_Init(void)
{
    PyIntObject *v;
    int ival;
    // 小整數(shù)池是否被激活
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
    for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++) {
        if (!free_list && (free_list = fill_free_list()) == NULL)
            return 0;
        /* PyObject_New is inlined */
        v = free_list;
        free_list = (PyIntObject *)Py_TYPE(v);
        (void)PyObject_INIT(v, &PyInt_Type);
        v->ob_ival = ival;
        small_ints[ival + NSMALLNEGINTS] = v;
    }
#endif
    return 1;
}

(上述代碼顯示,其實小整數(shù)內(nèi)存池也是通過block_list來管理的)

參考

《Python 源碼剖析》

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容