problem with PyMapping_SetItemString()

John Machin sjmachin at lexicon.net
Tue Apr 21 19:58:50 EDT 2009


On Apr 21, 5:25 pm, rahul <rahul03... at gmail.com> wrote:
> i have a c extension
>
> tatic PyObject *upadteCheck(PyObject *self,PyObject *args){
>         PyObject *var_pyvalue=NULL,*newVar_pyvalue=NULL,*dict=NULL;
>         char *varName;
>
>         if (!PyArg_ParseTuple(args, "s", &varName)){
>                 return NULL;
>       }
>           dict=PyEval_GetLocals();
>           var_pyvalue=PyMapping_GetItemString(dict,varName);
>
>           if(inObject==NULL){
>                 dict=PyEval_GetGlobals();
>                 var_pyvalue=PyMapping_GetItemString(dict,varName);
>           }
>
>           printf("\n input value for variable %s is :  %s
> \n",varName,PyString_AsString(var_pyvalue))
>
>           newVar_pyvalue=Py_BuildValue("s","value changed");
>
>           PyMapping_SetItemString(dict,varname,newVar_pyvalue);
>
>           return Py_BuildValue("");
>
> }
>
> and i have three  test cases for this extension
>
> 1.(name test1.py)
>          import upadteCheck
>          var1= "abcd"
>
>          func1():
>              updateCheck.updateCheck("var1")
>              print var1
>
> 2.(name test2.py)
>         import upadteCheck
>          var1= "abcd"
>          updateCheck.updateCheck("var1")
>          print var1
>
> 3.(name test3.py)
>          import upadteCheck
>
>          func1():
>              var1= "abcd"
>              updateCheck.updateCheck("var1")
>              print var1
>
> if i run these three test cases like
>  1.   import test1
>        test1.fun1()
>
>  2.   python test2
>
>  3. import test3
>      test3.func1()
>
> than first two test cases runs correctly and gives result for var1
> "value changed"  but 3rd test case not gives correct result and value
> of var1 remains "abcd"
>
> why this happen and how i correct it ??

Because you are trying to update a function's locals -- see this:
http://docs.python.org/library/functions.html?highlight=locals#locals

CPython's function locals are not stored in a dict, for efficiency
reasons. The dict that you get from locals() in Python or
PyEval_GetLocals() in C is constructed temporarily just for the
occasion. Changes to the dict are not reflected in the function's
locals.

Some general comments:

1. Either you have customised Python and C to forgive typos like
update / upadte and undeclared names like inObject, or you have the
annoying and counter-productive habit of re-typing (badly) what you
thought you ran, instead of using copy/paste.

2. Even if what you are attempting "worked", calling the function in
your extension appears to do no more that writing
   var1 = "changed value"
instead.

3. Why do you think you need to do what you are attempting? What
problem is it trying to solve? What need or requirement is it intended
to meet?



More information about the Python-list mailing list