1

I have a custom Sympy cSymbol class for the purpose of adding properties to declared symbols. This is done as follows:

class cSymbol(sy.Symbol):
    def __init__(self,name,x,**assumptions):
        self.x = x 
        sy.Symbol.__init__(name,**assumptions)

The thing is that when I declare a cSymbol within a function (say, it affects the property x of a cSymbol declared outside the function if the names are the same (here "a"):

def some_function():
    dummy = cSymbol("a",x=2)

a = cSymbol("a",x=1)
print(a.x)  # >> 1
some_function()
print(a.x)  # >> 2, but should be 1

Is there a way to prevent this (other than passing distinct names) ? Actually I am not sure to understand why it behaves like this, I thougt that everything declared within the function would stay local to this function.

Full code below:

import sympy as sy

class cSymbol(sy.Symbol):
    def __init__(self,name,x,**assumptions):
        self.x = x 
        sy.Symbol.__init__(name,**assumptions)
        
def some_function():
    a = cSymbol("a",x=2)


if __name__ == "__main__":
    a = cSymbol("a",x=1)
    print(a.x)  # >> 1
    some_function()
    print(a.x)  # >> 2, but should be 1
pfloutch
  • 23
  • 4
  • 1
    Related: [How to create two different sympy symbols with the same name](https://stackoverflow.com/q/73320484/11082165) – Brian61354270 Feb 11 '23 at 17:22
  • I have seen this post, but to me the problem is quite different ; here I have two sympy symbols with the same name, but _they are not supposed to interact_ (one is inside the function "some_function" and is not supposed to know anything about what is going on outside) – pfloutch Feb 11 '23 at 17:34
  • Isn't that exactly what `Dummy` is for? [Per the docs:](https://docs.sympy.org/latest/modules/core.html#dummy) _"Dummy symbols are each unique, even if they have the same name:"_ – Brian61354270 Feb 11 '23 at 17:35
  • 1
    Making a python symbol local to a python function, is not the same as making a symbol "local". `sympy` must be maintaining some sort of a symbol registry of its own. Likewise `sympy` expressions are not python functions. – hpaulj Feb 11 '23 at 18:10

1 Answers1

3

You aren't creating a local Python variable in the subroutine, you are create a SymPy Symbol object and all Symbol objects with the same name and assumptions are the same. It doesn't matter where they are created. It sounds like you are blurring together the Python variable and the SymPy variable which, though both bearing the name "variable", are not the same.

smichr
  • 16,948
  • 2
  • 27
  • 34