Joan Venge
Joan Venge

Reputation: 331102

How to pass values by ref in Python?

Basically I am using the C++ API of an app, but there is no reference for its python access. One variable is passed by ref, like so:

GetPoint ( Point  &p, Object obj )

so how can I translate to Python? Is there a pass by ref symbol?

Upvotes: 3

Views: 10268

Answers (5)

Aaron Maenpaa
Aaron Maenpaa

Reputation: 122910

There is no pass by reference symbol in Python.

Just modify the passed in point, your modifications will be visible from the calling function.

>>> def change(obj):
...     obj.x = 10
...
>>> class Point(object): x,y = 0,0
...
>>> p = Point()
>>> p.x
0
>>> change(p)
>>> p.x
10

...

So I should pass it like: GetPoint (p, obj)?

Yes, though Iraimbilanja has a good point. The bindings may have changed the call to return the point rather than use an out parameter.

Upvotes: 5

David Cournapeau
David Cournapeau

Reputation: 80730

There is not ref by symbol in python - the right thing to do depends on your API. The question to ask yourself is who owns the object passed from C++ to python. Sometimes, the easiest ting it just to copy the object into a python object, but that may not always be the best thing to do.

You may be interested in boost.python http://www.boost.org/doc/libs/1_38_0/libs/python/doc/index.html

Upvotes: 1

Iraimbilanja
Iraimbilanja

Reputation:

It's likely that your Python bindings have turned that signature into:

Point GetPoint(Object obj)

or even:

Point Object::GetPoint()

So look into the bindings' documentation or sources.

Upvotes: 3

Xolve
Xolve

Reputation: 23200

Objects are always passed as reference in Python. So wrapping up in object produces similar effect.

Upvotes: 1

Hank Gay
Hank Gay

Reputation: 71969

I'm pretty sure Python passes the value of the reference to a variable. This article can probably explain it better than I.

Upvotes: 2

Related Questions