0

I got the following problem. I have written a C-Extension to Python(2.7 / 3.2) to interface a self written software library. Unfortunately I need to return two values from the function where the last one is optional. In Python I tried

def func(x,y): 
    return x+y, x-y

test = func(13,4)    

but test is a tuple. If I write

test1,test2 = func(13,4)    

I got both values separated. Is there a possibility to return only one value without unpacking the tuple, i.e. the second(,.. third, ..fourth) value gets neglected?

And if such a solution existst, how does it look for the C-API? Because

return Py_BuildValue("ii",x+y,x-y); 

results in a tuple as well.

5
  • 1
    What version of python are you using? If I run your first snippet I do not get a single value, I get a 2-tuple as expected (and, IMO, is only sane--there are enough issues with not knowing return types in loosely typed languages without the return types changing depending on the call site!) Commented Nov 5, 2013 at 12:00
  • I reformulated the problem a bit more to point out the problem much better. Commented Nov 5, 2013 at 12:55
  • I see! I presume test, _ = func(...) isn't acceptable? I don't think this is something you're going to be able to do without a little syntactic overhead, unfortunately. Commented Nov 5, 2013 at 13:05
  • Addingg the addition dummy result _ will be an option, but I am interested in a "more elegant" way. Commented Nov 5, 2013 at 14:01
  • 1
    Append a [0] after the call. Commented Nov 5, 2013 at 14:54

1 Answer 1

2

This question is not special about the C API; this and the Python side behave consistently.

A tuple returned from a function can

  • be unpacked, if its length is constant: a, _ = f()
  • in 3.x, be unpacked, even if its length is not constant: a, *_ = f()
  • be iterated over, but that is not useful here
  • be indexed: a = f()[0].
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.