1

Python allows to return more than one result using commas as separating value.

When developing a CPython extension written in C language, is it possible to obtain the same result? How?

I'm developing a CPython extension that replaces an existing Python code to do some tests on performance and I will prefer to have the same interface to not change the existing code base.

I'm using Python 3.6.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Francesco Argese
  • 626
  • 4
  • 11
  • 1
    If you separate multiple values, python actually returns a single value (namely a Tuple) which contains the values you've provided. So you just need to handle the Tuple data type. – Basic Dec 04 '17 at 15:45

1 Answers1

5

Yes, you can create a tuple with PyTuple_New, populate it and return it. The callee will be able to unpack the result as usual.

Python returns multiple values by using containers. A single object is returned that is unpacked. Comma separated means tuple; in square brackets, on the other hand, a list is created. See How does Python return multiple values from a function for more on this.

If you'd like an example of how one might do this in C you can take a look at the implementation of str.partition or array.buffer_info (or any tuple returning built-in method).

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253