Sympy symbol to Symbolics.jl Num: adding a rule

I’m trying to convert a Sympy symbol into a Symbolics.jl Num type. When I use pyconvert_add_rule to add the rule, and then try to convert it using pyconvert, it says that it can’t convert the sympy symbol to a Symbolics Num. The function that I wrote to handle the conversion does what it’s supposed to, it’s just that it seems that adding the rule did not work.

using PythonCall
using Symbolics
using CondaPkg

CondaPkg.add("sympy")

sp = pyimport("sympy")

sympt = sp.Symbol("t")

typeof(Symbolics.variable(Symbol(pyconvert(Symbol,sympt.name))))

function pysym_to_Num(::Type{Symbolics.Num}, x::Py)
    PythonCall.pyconvert_return(Symbolics.variable(Symbol(pyconvert(Symbol,sympt.name))))
end

convertedt = pysym_to_Num(Symbolics.Num, sympt)

PythonCall.pyconvert_add_rule("sympy:Symbol",Symbolics.Num, pysym_to_Num)

PythonCall.pyconvert(Symbolics.Num, sympt)

So I had a stupid typo, and I thought that fixing it might help, but it did not. Here is the new function.

function pysym_to_Num(::Type{Symbolics.Num}, x::Py)
    if !pyisinstance(x,sp.Symbol)
        pyconvert_unconverted()
    end
    PythonCall.pyconvert_return(Symbolics.variable(Symbol(pyconvert(Symbol,x.name))))
end

The issue was not using the full name of the sympy symbol. It needs to be pyconvert_add_rule("sympy.core.symbol:Symbol",Symbolics.Num,pysym_to_Num)

I swear I thought I tried that before, maybe I was doing pyconvert_add_rule("sympy:core.symbol.Symbol",Symbolics.Num,pysym_to_Num) instead though.

1 Like