julia icon indicating copy to clipboard operation
julia copied to clipboard

confusing error thrown by `display`

Open stevengj opened this issue 1 year ago • 1 comments

The following example was noted on discourse. Suppose we define an ambiguous Base.show method for a new type because we forget to qualify the type of the io argument:

struct Foo; x; end
Base.show(io, x::Foo) = print(io, "FOO($(x.x))") # AMBIGUOUS io argument

Calling show directly correctly gives us a method-ambiguity error:

julia> show(Foo(3))
ERROR: MethodError: show(::Base.TTY, ::Foo) is ambiguous.

Candidates:
  show(io::IO, x)
    @ Base show.jl:457
  show(io, x::Foo)
    @ Main REPL[2]:1

but calling display gives us a very confusing error:

julia> display(Foo(3))
ERROR: MethodError: no method matching display(::Foo)

Closest candidates are:
  display(::Any)
   @ Base multimedia.jl:336
  display(::TextDisplay, ::MIME{Symbol("text/plain")}, ::Any)
   @ Base multimedia.jl:254
  display(::TextDisplay, ::Any)
   @ Base multimedia.jl:255
  ...

Stacktrace:
 [1] display(x::Any)
   @ Base.Multimedia ./multimedia.jl:347
 [2] top-level scope
   @ REPL[5]:1

probably because of the try-catch blocks inside display that try to figure out how to display an object.

Since text/plain output should always be available as a fallback, probably the display function should not try to catch errors from this. In particular, maybe https://github.com/JuliaLang/julia/blob/e89c21b3789ec5217e2b84a3ea4729b7b5c3d05b/base/multimedia.jl#L347 should be replaced by

show(stdout, MIME"text/plain"(), x) # fallback display

which has the added benefit that display(x) will now work even if the displays stack is empty.

stevengj avatar May 22 '24 14:05 stevengj

show(stdout, MIME"text/plain"(), x) # fallback display

The problem with this is that it is an odd fallback if you are running Julia on a device where display normally goes somewhere other than stdout. It would be better to be smarter about when to rethrow().

stevengj avatar May 22 '24 18:05 stevengj