title: I **really** need a function defined by user input. What are my options?
body: <p>I'm writing a Python script that parses a user-inputted string defining a differential equation, such as <code>'x\' = 2*x'</code>. My main problem is that I don't want to implement numerical solution methods myself, and instead rely on <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html#scipy.integrate.solve_ivp" rel="nofollow noreferrer">SciPy's solve_ivp method</a>, for which a function such as</p>
  <pre><code>def my_de(t, x):
      return 2*x
  </code></pre>
  <p>is absolutely necessary, since solve_ivp's first argument must be a function. Currently, I'm working around this problem with the following piece of code (in a simplified version):</p>
  <pre><code>var = 'x'
  de = '2*x'
  def my_de(t, y):
      exec(f'{var} = {y}')
      return eval(de)
  </code></pre>
  <p>A quick explanation for this terribleness: I do not know what variable the user's going to use in the input. <code>var</code> may be <code>theta</code>, it may be <code>sleepyjoe</code>, it may be <code>donalddump</code>. The only thing guaranteed is that the only variable on <code>de</code> is <code>var</code>. You can forget about <code>t</code> for the purposes of this post.</p>
  <p>My question is, how can I avoid using <code>exec</code> and <code>eval</code> in this context? I know using any of these is a terrible idea, and I don't want to do it. However, I'm not really seeing any other option.</p>
  <p>I am already parsing the user input beforehand, so I can try to make this safe (prohibited variable names, etc.), but anyone who wants to abuse this will be able to anyway.</p>