Recursive substitution in sympy
<p>I have a sympy expression with multiple variables that need to be substituted out. The problem is that the some of the expressions to be substituted in also contain instances of variables that need to be substituted out.</p>

<pre><code>from sympy import *
from sympy.abs import a,b, x,y

expr = a + b
replace = [[a, x+y], [b, 2*a]]

expr.subs(replace) # 2*a + x + y, I want 3*x + 3*y
</code></pre>

<p>If the replacement list is in the right order, it will apply each substitution sequentially, though in my real application I don't know what order would be appropriate:</p>

<pre><code>expr.subs(reversed(replace)) # 3*x + 3*y
</code></pre>

<p>I can force the substitution by applying the substitution n times to either <code>expr</code> or <code>replace</code>, but that seems computationally wasteful:</p>

<pre><code>result = expr
for _ in replace:
    # Applying n times
    result = result.subs(replace)
</code></pre>

<p>I was hoping for a <code>recursive</code> option to <code>subs</code>, but that doesn't seem to exist. Any better options?</p>