Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a variable as the input for a form field in Google Colaboratory?

The official example shows how to use Form Fields in Google Colaboratory: https://colab.research.google.com/notebooks/forms.ipynb.

Let's say we have a list: fruit_list = ['apples', 'bananas', 'mangoes']

Now I would like to add the elements of this list as a dropdown in the Form:

#@title # Select Your Choice of Fruit
fruit_selected = 'apples' #@params fruit_list {input: string}

As of now I can think of some hacks like this one:

#@title Boolean fields { run: "auto", vertical-output: true }
this_list = ["False", "True"]
boolean_checkbox = False #@param {type:"boolean"}
boolean_dropdown_asis = False #@param ["False", "True"] {type:"raw"}
boolean_dropdown_var = this_list[1] #@param {type:"raw"}

print(boolean_checkbox)
print(boolean_dropdown_asis)
print(boolean_dropdown_var)

But I would prefer to have another type of input: variable instead of just raw/string. The final implementation could be like this:

#@title # Select Your Choice of Fruit
fruit_list = ['apples', 'bananas', 'mangoes']
fruit_selected = 'apples' #@params fruit_list {input: variable}

I worked on some OVERKILL. You are free to look at it. Comments are welcome! :)

Anyone, any better idea?

Notes: There is another stackoverflow discussion where Sergio Lucero raised a similar question. But the main thread has a different question.

like image 788
CypherX Avatar asked Feb 13 '19 06:02

CypherX


People also ask

How do I add inputs in Google Colab?

You can just use input() . Then in another cell, you can use the name variable.

Does Google colab save variables?

The outputs of Colab cells shown in your browser are stored in notebook JSON saved to Drive. Those will persist. If you want to save your Python variable state, you'll need to use something like pickle to save to a file and then save that file somewhere outside of the VM.


1 Answers

If you use the widget like in the notebook of blois, you can use the following code to call the value:

fruit_picker.value

This will return the value of your chosen fruit.

The code in total will look like this:

import ipywidgets as widgets
fruit_list = ['pomegranate', 'watermelon', 'lychee']
fruit_picker = widgets.Dropdown(options=fruit_list, value='watermelon')

fruit_picker

fruit_picker.value
like image 147
Rein van Lennep Avatar answered Oct 05 '22 02:10

Rein van Lennep