JuliaCall: is it possible to pass objects from Python to Julia Main?

Using JuliaCall, is it possible to pass objects from Python to Julia so that I can then use them in evaluated Julia code ?

E.g.:

>>> from juliacall import Main as jl
>>> xpy = [1,2,3]
>>> jl.xj = xpy # AttributeError: 'ModuleValue' object has no attribute 'xj'
>>> s = jl.seval("sum(xj)") # this is where I want to arrive

Of course, I am aware I can simply do in this case:

>>> jl.sum(xpy)

but I wonder if I can explicitly transfer (possibly without manually using convert) objects from Python to Julia.

It’s admittedly not clear (I’ve now fixed this) but if you read down the full error stack the underlying error is:

AttributeError: Julia: cannot assign variables in other modules

which means that you can only assign a variable to a Julia module from code executing inside the module - this is a general Julia restriction.

If you really want you can write a function which uses @eval to do it:

>>> jlstore = jl.seval("(k, v) -> (@eval $(Symbol(k)) = $v; return)")
>>> jlstore("foo", [1,2,3])
>>> jl.foo
[1, 2, 3]
1 Like

Yes, it works:

>>> from juliacall import Main as jl
>>> xpy = [1,2,3]
>>> jlstore = jl.seval("(k, v) -> (@eval $(Symbol(k)) = $v; return)")
>>> jlstore("xj", xpy)
>>> s = jl.seval("sum(xj)")
>>> s
6

I think it would be useful to have this function in JuliaCall. Both PyJulia and R JuliaCall have something similar:

>>> jl = julia.Julia(compiled_modules=False)
>>> import julia
>>> from julia import Main
>>> xpy = [1,2,3]
>>> Main.xj = xpy
>>> jl.eval("sum(xj)")
6
> library(JuliaCall)
> xr = c(1,2,3)
> julia_assign("xj",xr)
> julia_eval("sum(xj)")
[1] 6
>