'sympy substitute all assigned variables

I declare a variable, define an expression using the variable

from sympy import *
x = symbols ('x')
f = 2 * x 

and then assign a value to the variable

x = 42

How can I substitute the variable in the expression by its current value? For obvious reasons

f.subs (x, x) 

does not work. I know that I can use a different variable

xx  = 42
f.subs (x, xx)

but ...

Nobody likes to get compared to their new girlfriend's ex, but in Matlab you could simply write subs (f) which would be the equivalent to SymPy's f.subs () without any parameters, to substitute all intermediately assigned variables.



Solution 1:[1]

per above,

>>> f = x**2
>>> x = 42
>>> def update(e):
...     d = globals()
...     return e.xreplace({x: eval(x.name, d) for x in e.free_symbols})
>>> Eq(f, update(f))
x**2 = 1764

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1