Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Collab How to show value of assignments?

I am working on this python notebook in Google Collab: https://github.com/AllenDowney/ModSimPy/blob/master/notebooks/chap01.ipynb

I had to change the configuration line because the one stated in the original was erroring out:

# Configure Jupyter to display the assigned value after an assignment

# Line commented below because errors out
# %config InteractiveShell.ast_node_interactivity='last_expr_or_assign'

# Edit solution given below
%config InteractiveShell.ast_node_interactivity='last_expr'

However, I think the original statement was meant to show values of assignments (if I'm not mistaken), so that when I run the following cell in the notebook, I should see an output:

meter = UNITS.meter
second = UNITS.second
a = 9.8 * meter / second**2

If so how can I make the notebook on google collab show output of assignments?

like image 932
Angel Cloudwalker Avatar asked Jun 06 '20 09:06

Angel Cloudwalker


2 Answers

The short answer is: you can not show output of assignments in Colab.

Your confusion comes from how Google Colab works. The original script is meant to run in IPython. But Colab is not a regular IPython. When you run IPython shell, your %config InteractiveShell.ast_node_interactivity options are (citing documentation)

‘all’, ‘last’, ‘last_expr’ , ‘last_expr_or_assign’ or ‘none’, specifying which nodes should be run interactively (displaying output from expressions). ‘last_expr’ will run the last node interactively only if it is an expression (i.e. expressions in loops or other blocks are not displayed) ‘last_expr_or_assign’ will run the last expression or the last assignment. Other values for this parameter will raise a ValueError.

all will display all the variables, but not the assignments, for example

x = 5
x
y = 7
y

Out[]:
5
7

The differences between the options become more significant when you want to display variables in the loop.

In Colab your options are restricted to ['all', 'last', 'last_expr', 'none']. If you select all, the result for the above cell will be

Out[]:
57

Summarizing all that, there is no way of showing the result of assignment in Colab. Your only option (AFAIK) is to add the variable you want to see to the cell where it is assigned (which is similar to regular print):

meter = UNITS.meter
second = UNITS.second
a = 9.8 * meter / second**2
a
like image 64
igrinis Avatar answered Sep 29 '22 21:09

igrinis


Google Colab has not yet been upgraded to the latest IPython version- if you explicitly upgrade with

!pip install -U ipython 

then last_expr_or_assign will work.

like image 33
Angel Cloudwalker Avatar answered Sep 29 '22 21:09

Angel Cloudwalker