[Python-Dev] A couple of quick type system questions

Thomas Heller thomas.heller@ion-tof.com
Mon, 13 May 2002 09:28:33 +0200


> > > ob_type has the type PyType_Object *, and a PyType_Object has a
> > > tp_dict pointer, so I think the answer is that every /type/ has a dict.
> > > 
> > Huh?
> > 
> > tp_dict of int (_PyInt_Type) is NULL.
> 
> Huh?  Not for me:
> 
> [guido@pcp742651pcs guido]$ python2.2
> Python 2.2.1 (#19, Apr 29 2002, 16:14:02) 
> [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> print int.__dict__.keys()
> ['__int__', '__ror__', '__rtruediv__', '__add__',

It seems tp_dict is lazily initialized:

Python 2.2.1 (#34, Apr  9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from get_dict import get_dict
>>> get_dict(int)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
SystemError: error return without exception set
>>> len(int.__dict__)
46
>>> get_dict(int)
{'__int__': <slot wrapper '__int__' of 'int' objects>, '__ror__': <slot wrapper '

Thomas

-----snip get_dict.c-----
#include "Python.h"

static PyObject *
get_dict(PyObject *self, PyObject *ob)
{
        PyTypeObject *tp;
        if (!PyType_Check(ob)) {
                PyErr_SetString(PyExc_TypeError,
                                "type expected");
                return NULL;
        }
        tp = (PyTypeObject *)ob;
        if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
                PyErr_SetString(PyExc_TypeError,
                                "not Py_TPFLAGS_HAVE_CLASS");
                return NULL;
        }
        Py_XINCREF(tp->tp_dict);
        return tp->tp_dict;
}

static PyMethodDef module_methods[] = {
        {"get_dict", get_dict, METH_O},
        {NULL,      NULL}        /* Sentinel */
};


DL_EXPORT(void)
initget_dict(void)
{
        Py_InitModule3("get_dict", module_methods, NULL);
}
---EOF---