__new__ is responsible for creating a new instance, not __call__ . __call__ just passes the instance creation work to __new__ and returns what __new__ returns, calling __init__ if necessary.
The best way to answer this type pun is to dig into the C code. Just download the source code, unzip it and vim Objects/typeobject.c or whatever you use to read and fiddle with the code.
If you look at it, you will find C implementations of all the components of the type metaclass. __new__ is grotesquely large, fiy.
def __call__(cls, *args, *kwds): will look like this:
Actual code C
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; } obj = type->tp_new(type, args, kwds); if (obj != NULL) { # if (type == &PyType_Type && PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 && (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) return obj; # if (!PyType_IsSubtype(obj->ob_type, type)) return obj; type = obj->ob_type; if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) && type->tp_init != NULL && type->tp_init(obj, args, kwds) < 0) { Py_DECREF(obj); obj = NULL; } } return obj; }
# added by me to help Stackoverflow syntax shortcut display comments correctly
Sample Python implementation
This is just a python explanation that I understand type.__call__ . This is not a re-implementation!
I may have missed some points as I am pretty new to the PyC API, so feel free to fix me. But I would execute it as follows:
def __call__(cls, *args, **kwds):
Final notes
- I would check the implementation of
__new__ (it was called type_new) - If you want to learn how Python works internally, try learning the C API and then reading the C source code.
- I am very new to Python C source code, so I may have missed something. Please correct me, does anyone know!