3

For some silly reasons, I recently needed to construct None.

My first attempt was to grab None's class and use it.

nt = type(None)

However, calling nt give this error:

nt()

TypeError: cannot create 'NoneType' instances

This gave me a chuckle and replaced that attempt with:

nt = lambda: None

This got me to thinking about why this doesn't work. I know that there is exactly one None for the interpreter, but this is also true of several other python objects and their constructors do not behave this way.

This SO question talks about about None and it's type heritage but as far as I can tell, this doesn't explain why type(None)() results in a TypeError.

I'm thinking that it must be related to some error checking that happens for return values of __new__ in metaclasses, but I'm not sure.

EDIT: Not a dup of Value of Py_None

That question asks "What is the c level value for the Py_None object in CPython?"

This question is specifically about "why does type(None)() produce a runtime error (TypeError)". type(None) gives us NoneType which is an instance of type. It is quite odd that calling this results in TypeError. As @metatoaster pointed out, this behavior is specific to 2.x. In 3.x NoneType() will produce None. This is the behavior I expect and apparently the core devs that made the change thought so too.

@metatoaster also provided a source link which look promising. It seems likely that this line is what is producing the runtime error message 'TypeError: cannot create 'NoneType' instances'. I did a regex search of the 2.7.14 tag in the cpython repo for cannot create .* instances and this line is the only result.

This is the context for the message:

static PyObject *
type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    PyObject *obj;

    if (type->tp_new == NULL) {
        PyErr_Format(PyExc_TypeError,
                     "cannot create '%.100s' instances",
                     type->tp_name);
        return NULL;
    }
...
}

There are a few places in the repo that set tp_new to NULL but none of them have anything to do with NoneType

Stephen
  • 2,613
  • 1
  • 24
  • 42

0 Answers0