Search code examples
javapythonchaquopy

Returning multiple lists from Python to Java using Chaquopy


How can I return multiple lists, values etc from my Python script to Java without ending up with a single object? Right now I end with a single PyObject with both returned values in it, and I haven't figured out how to divide them up again in Java.

Python:

import random

def calculations():

    res1 = [33, 13, 20, 34]

    list = [1,3,5,7]
    res2 = random.choices(list, k=10000)

    return res1, res2

Java:

if(!Python.isStarted())
            Python.start(new AndroidPlatform(getActivity()));

Python py = Python.getInstance();


PyObject obj = py.getModule("main").callAttr("calculations");

# How to extract the different objects from obj? Tried the following without success. 
List<PyObject> totList = obj.call(0).asList();
int[] data3 = obj.call(1).toJava(int[].class);

Solution

  • As the documentation says, call is equivalent to Python () syntax. But a tuple (which is what calculations returns) is not callable, so I assume that's the error you're receiving.

    Instead, you should do something like this:

    List<PyObject> obj = py.getModule("main").callAttr("calculations").asList();
    int[] res1 = obj.get(0).toJava(int[].class);
    int[] res2 = obj.get(1).toJava(int[].class);