Embedding Python - Passing by Reference

Neil Cerutti horpner at yahoo.com
Thu Nov 29 19:16:18 EST 2007


On 2007-11-29, andy at britishideas.com <andy at britishideas.com> wrote:
> I understand the parameters to Python functions are passed by
> reference:
>
> 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
> simplified):

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.

Python equivalent:

>>> def foo(x):
...   x[0] = 'foo'
...
>>> a = [0]
>>> foo(a)
>>> a
['foo']

-- 
Neil Cerutti



More information about the Python-list mailing list