title: Run a dynamic multi-line string of code in python at runtime
body: <p>How can I run a multi-line string of code from inside python, additionally the string is generated at runtime and stored in either a string or an array. </p>
  
  <p><strong>Background</strong></p>
  
  <ul>
  <li>I have a function which dynamically generates random code snippets in high volume.</li>
  <li>I wish to pass this code to a variable/string and evaluate syntax/return code.</li>
  <li>Code can not be imported from file/api request etc as focus is on high throughput and speed. </li>
  </ul>
  
  <p><strong>Example</strong></p>
  
  <pre><code># my function returns random code snippets
  myCode = myRandomCodeGenerator()
  
  # I wish to perform some in fight validation (ideally RC or syntax)
  someTestingFunction(myCode)
  </code></pre>
  
  <p><strong>My attempts so far</strong>    </p>
  
  <p>I have seen solutions such as the one below, however since my code is generated dynamically I have issues formatting. I have tried generating \n and \r or adding """ in the string to compensate with no luck. </p>
  
  <pre><code>code = """
  def multiply(x,y):
      return x*y
  
  print('Multiply of 2 and 3 is: ',multiply(2,3))
  """
  
  exec(code)
  </code></pre>
  
  <p>I have also tried using the <code>call</code> function on a string yields similar formatting issues. </p>
  
  <p>So far the best I can do is to perform a line by line syntax check and feed it a line at a time as shown below.  </p>
  
  <pre><code>import codeop
  def is_valid_code(line):
      try:
          codeop.compile_command(line)
      except SyntaxError:
          return False
      else:
          return True
  </code></pre>
  
  <p>I suspect there may be some syntax tricks I could apply to preserve formatting of indentation and returns. I am also aware of the risk of generating dynamic code in runtime, and have a filter of allowed terms in the function. </p>