Embedding Python - Passing by Reference
horpner at yahoo.com
Fri Nov 30 01:16:18 CET 2007
On 2007-11-29, andy at britishideas.com <andy at britishideas.com> wrote:
> I understand the parameters to Python functions are passed by
> def foo(a):
> a = a + 1
> Will change the value of a in the calling function. How do I
> implement the equivalent in C when extending Python?
You've got the passing convention basically correct, but the
semantcs of 'a + 1' wrong.
'a + 1' evaluates to a new integer object equal to a+1. Then the
= binds the local a to that new integer. The object that
the calling a refers to is never modified, and the name that is
bound to it is not rebound.
If you had modified the object that the local a was bound to, it
would have the effect you are after. As it happens, some objects
are immutable and thus cannot be modified.
> I know how to write a function that can be called from Python
> and I know how to use PyArg_ParseTuple to get the value of a.
> But how do I update the value of a in C? I tried (greatly
You cannot do it. You'll have to insist on a boxed value of some
kind, like one stored in a list or an object.
>>> def foo(x):
... x = 'foo'
>>> a = 
More information about the Python-list