C API: Change immutable objects? :-o

Frank Sonnenburg frank.sonnenburg at biosolveit.de
Fri Aug 2 11:52:07 EDT 2002

Hi there

I'm trying to speed up updating my PyObjects, e.g. PyFloat.

So instead of deleting the old object and creating a new one with my new 
double value, i over-write the old value in the PyFloatObject-struct:

#include "python/Python.h"
#include <stdlib.h>

PyObject *change_float(PyObject *self, PyObject *args)
  PyObject *pyval;

  if (!PyArg_ParseTuple(args, "O!", &PyFloat_Type, &pyval))
    return NULL;

  /* over-write old value */
  ((PyFloatObject *) pyval)->ob_fval = 3.14159;

  return Py_BuildValue("");

PyMethodDef methods[] = {
  {"change_float", change_float, METH_VARARGS},

void initnewmodule(void)
  Py_InitModule("newmodule", methods);

Executing is fine, as desired:

>>> import newmodule
>>> f=3.0
>>> newmodule.change_float(f)
>>> f

But maybe this is very risky i assume?? If this would be all right, there 
would have been an explicit API-call!?

I'm very afraid in using this because handling for example integers in this 
manner would cause serious problems in some circumstances. Small integer 
objects are predefined and changing their values would have unpredictable 

Are there some cases, where proceeding as described is not dangerous? Or do 
you say: NEVER, you will always get trouble with this!?

Thanks in advance


More information about the Python-list mailing list