Skip to content

using assignment expressions to display and assign in IPythonยค

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

    shell = get_ipython()

by default, shell.ast_node_interactivity displays the last expressions

    shell.ast_node_interactivity
'last_expr'

the other 5 options follow the code below

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

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.

    my_variable = 42; my_variable
42

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

    (my_variable := 42)
42

it feels lispy and i like it.

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