Stream: helpdesk (published)

Topic: Show custom type - all the bells and whistles


view this post on Zulip Kevin Bonham (Sep 09 2021 at 14:52):

I've definitely asked variants of all of these questions before, but every time it comes up, I get confused again. Is there anywhere I can read a comprehensive guide to dealing with the way my custom type is displayed? I've read around the manual (eg here and here), and at one point I tried to read through the issue a couple of versions ago where the representation of vectors was changed, but I remain confused about:

  1. What are the different MIME types? Which ones make sense to support?
  2. What do I need to consider for IOContext? Eg. I think I'll want do deal with :compact and :limit, in particular, but how would I know?
  3. What's the difference between what happens when a type is displayed at the REPL, when I call print(thing), when I call show(thing), when I call @show thing, or when I write thing to a file? Eg
julia> a = rand(3)
3-element Vector{Float64}:
 0.20666407638083917
 0.0861516328854468
 0.5337028655172353

julia> print(a)
[0.20666407638083917, 0.0861516328854468, 0.5337028655172353]
julia> show(a)
[0.20666407638083917, 0.0861516328854468, 0.5337028655172353]
julia> @show a
a = [0.20666407638083917, 0.0861516328854468, 0.5337028655172353]
3-element Vector{Float64}:
 0.20666407638083917
 0.0861516328854468
 0.5337028655172353

julia> path, io = mktemp()
("/tmp/jl_Fxk9CS", IOStream(<fd 24>))

julia> write(io, a)
24

julia> close(io)

shell> cat $path
�(���s�? p�^N�?F�^X^T�?

julia> path, io = mktemp()
("/tmp/jl_Onx4qM", IOStream(<fd 22>))

julia> print(io, a)

julia> close(io)

shell> cat $path
[0.20666407638083917, 0.0861516328854468, 0.5337028655172353]
  1. How do I write unit tests for the display?

view this post on Zulip Fredrik Ekre (Sep 09 2021 at 15:33):

  1. There are lots, see for example https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types). Which ones you want to support, well, I guess it is up to you. A text/plain is essentially required though. And if your object can display pretty in HTML for example, then why not support that too.

  2. I believe IOContext is only used for text/plain, and then I am only aware of :compact, :limit, and :color.

  3. write writes a binary representation (hence the garbage). print defaults to show, @show calls show (through repr).

  4. Non text/ mimes are difficult to test I guess, but otherwise e.g. sprint (sprint(show, MIME"text/plain"(), a))


Last updated: Nov 22 2024 at 04:41 UTC