Search code examples
pythonfunctionsympy

Trying to write a python function with a default sympy symbol


I am trying to write a function that has a sympy symbol with a default value, but am not getting what I expect.

Here is my code

import sympy as sy
def addtwo(y = sy.symbols('y', reals = True)):
    return y + 2

y = sy.symbols('y')
x = addtwo()
print(type(x))
print(x)
print(x.subs(y,1))

with output

<class 'sympy.core.add.Add'>
y + 2
y + 2

However, the code

y = sy.symbols('y')
x = addtwo(y)
print(x)
print(x.subs(y,1))

gives the expected output

y + 2
3

Solution

  • Consider these two symbols: y1 = sy.symbols('y') and y2 = sy.symbols('y'). Even though they are created at different times, they are equals: they have the same name and the same assumptions (none in this case, they are just complex symbols). Now consider y3 = sy.symbols('y', real=True), which has the same name but different assumptions. So y3 is different from y1, y2.

    Going back to your first example, the substitution doesn't work because the symbol you created inside the function is different from the symbol you created outside. Said differently, the symbol you created outside is not contained in the expression.

    Because you are dealing with an expression containing only one symbol, one possible solution is to retrieve it from the set of symbols contained in the symbolic expression, like this:

    import sympy as sy
    def addtwo(y = sy.symbols('y', reals = True)):
        return y + 2
    
    x = addtwo()
    # .free_symbols returns a set of symbols contained in the symbolic expression
    my_y = x.free_symbols.pop()
    print(type(x))
    print(x)
    print(x.subs(my_y,1))