Output-like print

question

#1

Compare this:

image

to this:

image

or this:

image

How can I “print” a value, to be formatted like it would if it was output (like in the first case)?

The problem with just outputing (like in the first case) is that you can only do it once per cell, since only the last expression is returned. I would like to print multiple values (with output format) from the same cell.


#2

I think you want display:

julia> display(Dict(i => i^2 for i = 1:5));
Dict{Int64,Int64} with 5 entries:
  4 => 16
  2 => 4
  3 => 9
  5 => 25
  1 => 1

#3

For some reason it doesn’t respect the order in which I print things.

image

Any idea how I can resolve that?


#4

Try

julia> show(STDOUT, MIME("text/plain"), Dict(1=>2, 2=>3))
Dict{Int64,Int64} with 2 entries:
  2 => 3
  1 => 2

#5

What you’re seeing is the difference between the two-argument show(io, x) (called by print) and the three-argument show(io, "text/plain", x) (called by display). See https://docs.julialang.org/en/stable/manual/types/#Custom-pretty-printing-1


#6

Why the order between print and display calls is not respected?


#7

In IJulia/Jupyter, print output (i.e. stdio output) and display output use different mechanisms.

STDOUT is flushed to the notebook display via “stream” output messages. This only happens at certain intervals — every print statement does not trigger an individual stream message.

Each display call, on the other hand, sends an individual “display_data” message. This is because display(x) output is not limited to text: for a given x, it outputs in the richest format supported by x and by Jupyter. e.g. it could output an image or a LaTeX-formatted equation.

As a result, display and print outputs do not necessarily appear in order.

In general, you cannot assume that display output goes to STDOUT, unlike print. e.g. display(x) may open up a separate window with an image, etcetera. display(x) means “show x in the best way you can for the current output device(s)”. If you want REPL-like text output that is guaranteed to go to STDOUT, use show(STDOUT, "text/plain", x) instead.


#8

Thanks for the answer.