Implementation of NoneType, Reasons and Details

后端 未结 4 1145
灰色年华
灰色年华 2021-01-11 15:53

I recently read somewhere that the special value None in python is a singleton object of its own class, specifically NoneType. This explained a lot

4条回答
  •  春和景丽
    2021-01-11 16:33

    Other answers describe how to use __new__ to implement a singleton, but that's not how None is actually implemented (in cPython at least, I haven't looked into other implementations).

    Trying to create an instance of None through type(None)() is special cased, and ends up calling the following C function:

    static PyObject *
    none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
    {
        if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) {
            PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
            return NULL;
        }
        Py_RETURN_NONE;
    }
    

    And Py_RETURN_NONE is defined here:

    /*
    _Py_NoneStruct is an object of undefined type which can be used in contexts
    where NULL (nil) is not suitable (since NULL often means 'error').
    
    Don't forget to apply Py_INCREF() when returning this value!!!
    */
    PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */
    #define Py_None (&_Py_NoneStruct)
    
    /* Macro for returning Py_None from a function */
    #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
    

    Contrast this with the function that creates a normal python object:

    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);
    }
    

    When you create a normal object, memory for the object is allocated and initialized. When you try to create a new instance of None, all you get is a reference to the already existing _Py_NoneStruct. That's why, no matter what you do, every reference to None will be the exact same object.

提交回复
热议问题