title: IPython Notebook Javascript: retrieve content from JavaScript variables
body: <p>Is there a way for a <strong>function</strong> (called by an IPython Notebook cell) to retrieve the content of a JavaScript variable (for example <code>IPython.notebook.notebook_path</code> which contains the path of the current notebook)?</p>
  
  <p>The following works well when written directly within a cell (for example, based on <a href="https://stackoverflow.com/a/23619544/758174">this question</a> and its comments):</p>
  
  <pre><code>from IPython.display import display,Javascript
  Javascript('IPython.notebook.kernel.execute("mypath = " + "\'"+IPython.notebook.notebook_path+"\'");')
  </code></pre>
  
  <p>But that falls apart if I try to put it in a function:</p>
  
  <pre><code># this doesn't work
  from IPython.display import display,Javascript
  def getname():
      my_js = """
      IPython.notebook.kernel.execute("mypath = " + "\'"+IPython.notebook.notebook_path+"\'");
      """
      Javascript(my_js)
      return mypath
  </code></pre>
  
  <p>(And yes, I've tried to make <code>global</code> the <code>mypath</code> variable, both from within the <code>my_js</code> script and from within the function. Also note: don't be fooled by possible leftover values in variables from previous commands; to make sure, use <code>mypath = None; del mypath</code> to reset the variable before calling the function, or restart the kernel.)</p>
  
  <p>Another way to formulate the question is: "what's the scope (time and place) of a variable set by <code>IPython.notebook.kernel.execute()</code>"?</p>
  
  <p>I think it isn't an innocuous question, and is probably related to the mechanism that IPython uses to control its kernels and their variables and that I don't know much about.  The following experiment illustrate some aspect of that mechanism. The following works when done in two separate cells, but doesn't work if the two cells are merged:</p>
  
  <p><strong>Cell [1]</strong>:</p>
  
  <pre><code>my_out = None
  del my_out
  my_js = """
  IPython.notebook.kernel.execute("my_out = 'hello world'");
  """
  Javascript(my_js)
  </code></pre>
  
  <p><strong>Cell [2]</strong>:</p>
  
  <pre><code>print(my_out)
  </code></pre>
  
  <p>This works and produces the expected <code>hello world</code>. But if you merge the two cells, it doesn't work (<code>NameError: name 'my_out' is not defined</code>).</p>