Jupyter notebooks (formerly iPython) are becoming an ever useful tool for many people, especially those working in a scientific field. There are a number of specific techniques that enhance their utility, and I’ll try to post details of these over the next few weeks. One useful tip involves how to use variables within widgets in notebooks.
When creating variables for use within Jupyter (iPython) notebooks you need two widgets, one for input, and another to bind the value of that input. A screenshot of this in action, binding variables from ipywidgets Text() and interact() for use throughout the notebook is shown here:
The python code required to make this happen is explained here:
from ipywidgets import widgets
# Create text widget for output
output_variable = widgets.Text()
# Create text widget for input
input_text = widgets.Text()
# Define function to bind value of the input to the output variable
def bind_input_to_output(sender):
output_text.value = input_text.value
# Tell the text input widget to call bind_input_to_output() on submit
input_text.on_submit(bind_input_to_output)
# Display input text box widget for input
input_text
# Display output text box widget (will populate when value submitted in input)
output_text
# Display text value of string in output_text variable
output_text.value
# Define new string variable with value of output_text, do something to it
uppercase_string = output_text.value.upper()
print uppercase_string
You can then use the uppercase_string, or output_text.value string, for example, throughout your notebook.
A similar pattern can be followed for using other input values, e.g. the interact() slider:
from ipywidgets import widgets, interact
# Create text widget for output
output_slider_variable = widgets.Text()
# Define function to bind value of the input to the output variable
def f(x):
output_slider_variable.value = str(x)
# Create input slider with default value = 10
interact(f, x=10)
# Display output variable in text box
output_slider_variable
# Create and output new int variable with value of slider
new_variable = int(output_slider_variable.value)
print new_variable
# Do something with new variable, e.g. cube
new_variable_cubed = pow(new_variable, 3)
print new_variable_cubed
There is a good introduction to this whole topic at ipywidgets at http://blog.dominodatalab.com/interactive-dashboards-in-jupyter/ from where a lot of this information was gained.
You can also see a StackOverflow post, where this is an answer to a question on the topic here.