I have an AbstractArray
type with its own display
method that gets called correctly in the REPL but in Jupyter/IJulia whatever function is called to display the last argument in each cell is apparently calling a default display type for AbstractArray
rather than my object’s specialized method. What display
type function is called at the end of each cell?
Here is a MWE where the exact same code displays differently in the REPL and in IJulia:
struct SqrV <: AbstractArray{Int, 1}
count::Int
end
Base.size(S::SqrV) = (S.count,)
Base.IndexStyle(::Type{<:SqrV}) = IndexLinear()
Base.getindex(S::SqrV, i::Int) = i*i
Base.display(s::SqrV) = println("SV1 count=$(s.count)")
Base.Multimedia.display(d::AbstractDisplay, s::SqrV) = println("SV2 $(s.count)")
Base.Multimedia.display(d::AbstractDisplay, m::MIME, s::SqrV) = println("SV3 $(s.count)")
s = SqrV(4)
1 Like
IJulia calls display
, but with its own AbstractDisplay
type, so your method isn’t being called.
The problem is that you shouldn’t be overriding display
in the first place. You should override show
, as is explained in the manual. For example:
Base.show(io::IO, s::SqrV) = print(io, "SV1 count=$(s.count)")
Base.show(io::IO, m::MIME"text/plain", s::SqrV) = print(io, "SV2 $(s.count)")
Then if you do print(s)
it will use the first method, whereas REPL display
and IJulia will use the second method, as is explained in the manual.
Note that you want to call print(io, ...)
in show
, not println(....)
. First, show
output does not typically include a trailing newline (that is added when show
is called, e.g. by println
). Second, you want to output to the supplied io
stream — that way your custom show
method can work with streams besides stdout
(e.g. output to a file or buffer).
5 Likes
Thanks so much! I hadn’t realized that from the display
documentation so I made a 1-line PR to that I hope might save others from the same question:
https://github.com/JuliaLang/julia/pull/34438
3 Likes