I find difficult to really encapsulate a lot of logic in a reusable manner when writing sympy
code
I would like to write a function in the following way:
def compute_integral(fn):
s = symbols_new() # do not apply lexicographic identity, this symbol identity is unique
return integrate( fn(s), (s, 0, 1))
If I just use the usual symbols()
to instantiate s
, I risk fn
having the same symbol inside its defining expression somewhere, for instance the following can occur:
def compute_integral(fn):
s = symbols("s")
return integrate(fn(s), (s, 0, 1))
...
import sympy as sp
from sympy.abc import *
t = sp.sin(3 + s)
f = sp.lambdify([x], x**2 + t * s * x)
compute_integral(f) #< ---- symbol s is already present in the function, now the integral will produce the wrong result
What I’m doing right now to minimize this issue is less than ideal:
compute_integral_local_var = 0
def compute_integral(fn):
global compute_integral_local_var
compute_integral_local_var += 1
s = symbols("local_{}".format(compute_integral_local_var))
return integrate(fn(s), (s, 0, 1))
I want to avoid these kind of collisions without having to add a special global variable. Any better approaches to achieve this type of encapsulation within the sympy
API?
1