Scope and use of a var in a python function

26 views
Skip to first unread message

John Lockwood

unread,
Nov 17, 2025, 4:56:29 PM (6 days ago) Nov 17
to sage-support
Hi,

I am writing some Python functions using SageMath (with the SageMath Kernel 10.7 on Mac, in Jupyter Lab).  I have a question about how to safely pass vars into a Python function, if it's possible at all.  The intent is to make the function usable no matter what variable the caller chooses for his function.  The issue shows up in the substitute function, but of course I'd like the solution to work in other contexts as well.  (At least in some cases, it seems to).  Is there another way to approach this?  

Thanks!

Here's a highly simplified example that shows the issue:

def example_reasonable(fn, variable, value):
    """This is a simple example showing the issue; this example doesn't work"""
    # print(variable) 
    # prints u as expected....
    # but this substitution doesn't work
    return fn.substitute(variable=value)

def example_works(fn, value):
    return fn.substitute(u=value)

u = var('u')
f = u^2 + 7*u
print(example_reasonable(f, u, 3))  # Output should be 30, is just function
print(example_works(f, 3))               # Output should be 30, and is 30

Output:
u^2 + 7*u 30

Nils Bruin

unread,
Nov 17, 2025, 10:28:28 PM (6 days ago) Nov 17
to sage-support
That's why subs can also accept a dictionary argument, where you don't have to rely on the python name matching the symbol name:

def example_works_too(fn, var, val):
    return fn.subs({var:val})

The "keywords" based version is just a convenience for interactive work. A substitution dictionary (where the keys can actually be the symbols!) is the more general interface. It's documented in x.subs. You can see from the documentation of x.substitute that "subs" is the main routine, since it refers you there.

John Lockwood

unread,
Nov 18, 2025, 11:30:18 AM (5 days ago) Nov 18
to sage-support
Nils,

Yes, that works quite well both in the example and in my original cases.  Thanks so much for the prompt assist.

John

Reply all
Reply to author
Forward
0 new messages