skip to main content

@tonyfast s notebooks

site navigation
notebook summary
title
using assignment expressions to display and assign in IPython
description
not all notebok users are aware that there are different implicit display conditions that can be configured with IPython with the ast_node_interactivity option
cells
13 total
6 code
state
executed out of order
kernel
Python [conda env:root] *
language
python
name
conda-root-py
lines of code
17
outputs
5
table of contents
{"kernelspec": {"display_name": "Python [conda env:root] *", "language": "python", "name": "conda-root-py"}, "language_info": {"codemirror_mode": {"name": "ipython", "version": 3}, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.13"}, "title": "using assignment expressions to display and assign in IPython", "description": "not all notebok users are aware that there are different implicit display conditions\nthat can be configured with IPython with the ast_node_interactivity option"}
notebook toolbar
Activate
cell ordering
1

using assignment expressions to display and assign in

2

not all notebok users are aware that there are different implicit display conditions that can be configured with IPython with the ast_node_interactivity option

3
    shell = get_ipython()
4

by default, shell.ast_node_interactivity displays the last expressions

5
    shell.ast_node_interactivity
1 outputs.
'last_expr'
6

the other 5 options follow the code below

7
    shell.traits()["ast_node_interactivity"].values
1 outputs.
['all', 'last', 'last_expr', 'none', 'last_expr_or_assign']
8

sometimes when i am debugging i want to store a variable and display it at the same. the IPython approach set shell.ast_node_interactivity = "last_expr_or_assign" . admittedly, i never choose this because i don't want it all the time, just while debugging.

what i do instead is set the variable and append an implicit display at the end.

9
    my_variable = 42; my_variable
1 outputs.
42
10

i've shifted from this approach to using assignment expressions with make more sense.

11
    (my_variable := 42)
1 outputs.
42
12

it feels lispy and i like it.

13
    (button := __import__("ipywidgets").Button(description="a butt"))
1 outputs.
Button(description='a butt', style=ButtonStyle())