Why automatic display of variable is not run when is is in a context? InteractiveShell

If I have a variable as last one in the cell, it is displayed automatically:

a = 5
a

Shows 5.

But if I wrap this in a context, it no longer displays:

a = 5
with pd.option_context('display.max_columns', 10):
    a

Nothing is shown.

I know there is an option to configure InteractiveShell to show all variables, but this is not what I’m looking for. I would like to understand why the context manager prevents the default option of InteractiveShell from displaying a

Thank you !

The last line is special. I think of it like in the notebook where it automatically returns the value of the last line. I like the way kynan’s comment here states it in regard to the use of ; sometimes at the end of the last line to suppress certain output:

" The reason this works is because the notebook shows the return value of the last command. By adding ; the last command is “nothing” so there is no return value to show"

In the case of your context example, the last line is indented and in the scope of the with statement so nothing gets returned. Similar to if you had been in a function definition as the last line of a cell.

You can get it to show the value from inside the context using:

a = 5
with pd.option_context('display.max_columns', 10):
    display(a)

Or:

a = 5
with pd.option_context('display.max_columns', 10):
    print(a)

Perhaps someone else can fill in more technical reasoning, but that is how I understand it, that the REPL- model is tied to the last line.

1 Like

As you suggest, the output displays the value of the final object that is returned when the code in the code cell is executed. In the example, that’s the return value of the with pd.option_ statement, which doesn’t return anything.

2 Likes