Write access to python numpy arrays encapsulated in a list from julia with PyCall

Dear julianers,
I am facing an issue trying to use a library I have in Python inside Julia.
In particular, I need to modify the elements of a numpy array, which is stored inside a Python list from Julia using PyCall. However, PyCall automatically converts all Python objects into Julia objects by making copies of the data, thus not allowing for editing the original Python object.
In particular, I have the following object dyn, that has an attribute dynmats which is a list of numpy arrays (a matrix). I want to modify the element in such a way:

dyn.dynmats[i][j, k] = my_value

Indeed, this simple code does not modify the original python object. I can use

dyn."dynmats"[i][j, k] = my_value

So that the first list is correctly returned without wrapping around a Julia Vector. However, when I access the i-th element of dynmats, the numpy matrix is converted into a Julia Matrix by copying the data, thus still preventing editing it. I have tried multiple routes, as using the python __get_item__ on the list, but also in this case, PyCall wraps the Python object around a julia array copying the data.

Is there a way to directly the elements of a Python list without converting to Julia objects?

You can get the python array as a PyArray instead, which is a mutable wrapper around the underlying data.

Or you can use PythonCall which does non-copying conversion by default (and also has a similar PyArray wrapper type).

1 Like

You can tell it not to convert, e.g. by calling a Python function with the pycall function and specifying the return type as PyObject.

As noted above, the alternative PythonCall package doesn’t convert by default.