Changing the passed arguments value after returning from a module

Adrian Eyre a.eyre at optichrome.com
Fri Jan 21 09:08:20 EST 2000


> I'm trying to write a C module that changes the values of a passed
> argument, which I am sure is a classic problem. The Python script
> would look as:
> 
>     import mymodule
>     i=0
>     mymodule.test( i )
>     print i

You have to really mess with Python's internals to do that. I'm
assuming you only want to change integers here.

/* N.B.: Not tested */
static PyObject* sct_tt( PyObject* zself, PyObject* args)
{
    PyObject* o;    
    if (!PyArg_ParseTuple(args, "O", o))
         return NULL;
    ((PyIntObject*) o)->ob_ival = 101;
    Py_INCREF(Py_None);
    return Py_None;
}

Be *very* careful if you intend to do this though:

1. You are dealing with undocumented intefaces, and cannot rely on
   this being the same in later releases.

2. Python caches several small integers (not sure how many), so this
   code would actually change all integer variables with the value 0
   to the value 101.

>>> import mymodule
>>> i = 0
>>> j = 0
>>> mymodule.test(i)
>>> print i
101
>>> print j
101

Also... the reason why your version does not work is that you are
changing the tuple used when the function is called. This goes out
of scope as soon as the function exits. It would work if you did:

>>> import mymodule
>>> i = (0,)
>>> apply(mymodule.test, i)
>>> print i
101

--------------------------------------------
Adrian Eyre <a.eyre at optichrome.com>
http://www.optichrome.com 





More information about the Python-list mailing list