2

Good evening guys,

yesterday I found out that we can use Chaquopy to run Python scripts from Java. I have played around with it a little bit and came across the following problem:

ArrayList-Objects (resp. LinkedList-Objects), which I have passed to a Python script, do not behave as I would expect it. In Python, I can't just use list[index] with an ArrayList, that comes from Java. The following exception is thrown:

com.chaquo.python.PyException: TypeError: 'LinkedList' object is not subscriptable

I have looked at the Chaquopy-Documentation and couldn't find any information about Java-List support. Only arrays are stated there.

Now my question: Do I have to convert all my lists to arrays in Java before passing them to Python?

Thank you all

2
  • Probably convert any LinkedList objects to ArrayList. Just speculating. Commented Feb 4, 2021 at 17:13
  • First of fall, thank you for your response. Sadly, that's not working. Maybe I didn't make it clear enough: the problem occurs in both cases, linkedlists as well as arraylists. I will add a code example to my question to clarify it. Commented Feb 4, 2021 at 19:31

1 Answer 1

1

You're right, Chaquopy supports accessing Java arrays using Python syntax, but not Java Lists. You can either:

  • Copy the List to an array using toArray, and pass that to Python; or
  • Pass the List to Python and have the Python code call its methods directly (i.e.size, get, etc.).
Sign up to request clarification or add additional context in comments.

3 Comments

Meanwhile, I figured that out by myself, but anyways thanks for that clarification.
Maybe you could answer me one additional question: is it somehow possible to cast PyObjects that contain Python matrices to Java Lists/Arrays in Java without iterating through each element? What’s the best practice here?
Any iterable Python object can be converted to a compatible Java array type using toJava. But if the object implements the buffer protocol, and the Java array is of the matching type, then the conversion will be more efficient. For example, if your object is a NumPy int16 array, then toJava(short[].class) will be very fast, while toJava(int[].class) will also work, but much more slowly.

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.