Has anyone tried setting class attributes on a new-style class in C? The file sandbox/datetime/datetime.py has code that does this:
class datetime(basetime): ...
datetime.min = datetime(...) datetime.max = datetime(...)
I can easily add descriptors in the C version so that min and max are defined on instances, but using PyObject_SetAttrString() using the new class:
tmp = create_datetime(...); if (datetime_min == NULL) return; if (PyObject_SetAttrString((PyObject *) &PyDateTime_Type, "min", datetime_min) < 0) return;
produces this exception:
Traceback (most recent call last): File "test_cdatetime.py", line 9, in ? from _datetime import datetime, MINYEAR, MAXYEAR TypeError: can't set attributes of built-in/extension type 'datetime.datetime'
(where _datetime is the C extension that implements the C version of the type).
Type objects declared statically (as a pre-initialized static or global C struct) are considered immutable. If you want to modify the dict during module initialization in C, you can access it as the tp_dict member of the type object. It is initialized by PyType_Ready(). The subclass trick that Jeremy mentioned is good if you need to do it in Python. I think it works David Abraham because he has a custom metaclass; this approach doesn't apply to adding types to the core language. --Guido van Rossum (home page: http://www.python.org/~guido/)