Ask Your Question
2

Is there a way to define local symbolic variables inside functions that do not overwrite global ones?

asked 2025-10-16 13:05:56 +0100

razimantv gravatar image

Consider the behaviour of the following function:

k, c = var('k c')

q = k * c
show(q)

def dummy():
    q = 4

dummy()
show(q)

Before and after the function runs, q stores kc.

But now consider the function

k, c = var('k c')

q = k * c
show(q)

def dummy():
    q = var('q')

dummy()
show(q)

But now, after the function returns, the value of q has changed to q.

How can I write a "safe" function such that any dummy variable I create inside does not overwrite a global variable? reset() and restore() both result in an undefined error.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
5

answered 2025-10-16 16:41:40 +0100

eric_g gravatar image

You should use q = SR.var('q') instead of q = var('q'). Indeed, var('q') injects q in the global namespace, while SR.var('q') does not.:

def dummy():
    q = SR.var('q')
edit flag offensive delete link more

Comments

Thank you. After looking at the documentation for SR, it seems that SR.temp_var() would serve my purpose even better.

razimantv gravatar imagerazimantv ( 2025-10-17 12:42:40 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2025-10-16 13:05:56 +0100

Seen: 113 times

Last updated: Oct 16