Returning symbolic variable from modeul

The following code works if you run it directly in REPL

module MyM
using SymPy
export beta, return_beta
beta = symbols("β")
function return_beta()
    return -beta
end
end
MyM.return_beta()

But if you put MyM in a file MyM.jl and use it like this

using MyM; return_beta()

you will see an error

ERROR: ArgumentError: ref of NULL PyObject
Stacktrace:
 [1] getproperty(::PyCall.PyObject, ::String) at /home/xing/.julia/packages/PyCall/zqDXB/src/PyCall.jl:296
 [2] getproperty(::PyCall.PyObject, ::Symbol) at /home/xing/.julia/packages/PyCall/zqDXB/src/PyCall.jl:306
 [3] getproperty(::SymPy.Sym, ::Symbol) at /home/xing/.julia/packages/SymPy/JaxDZ/src/types.jl:119
 [4] -(::SymPy.Sym) at /home/xing/.julia/packages/SymPy/JaxDZ/src/mathops.jl:10
 [5] return_beta() at /home/xing/Dropbox/Research/2020/Bak-Sneppen/MyM.jl:6
 [6] top-level scope at REPL[1]:1

I also tried similar code with SymEngine.jl, exactly the same problem. Is there something wrong about my code?

The problem with beta is that the underlying memory is freed when you load it from file. You need to assign beta in the __init__ function of your module.
See here how SymEngine.jl handles this.

3 Likes