Wednesday, April 6, 2011

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?

From stackoverflow
  • 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.

    Joan Venge : So I should pass it like: GetPoint (p, obj)?
  • I'm pretty sure Python passes the value of the reference to a variable. This article can probably explain it better than I.

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

    Salim Fadhley : This is the correct answer. Python objects are always passed in the same way (by reference). Some objects (e.g. ints) are immutable and give the impression of being passed by value... nope, it's ways the same way.... always! :-)
  • 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.

    Joan Venge : Thanks, the return is a bool for status, but the point must be passed, otherwise, it throws wrong number of args exception.
  • 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

0 comments:

Post a Comment