Show for supertype

I am trying to organize printing for a set of types the following way: a generic function returns a string representation, then show for the supertype just prints it. MWE:

abstract type MyAbstractFun <: Function end
Base.show(io::IO, f::MyAbstractFun) = println(io, representation(f))
struct One <: MyAbstractFun end
(::One)(x) = x+1
representation(::One) = "just adds one"

but then evaluating at the REPL (ie going through display) gives me the standard printing from Base, while show works correctly:

julia> One()
(::One) (generic function with 1 method)

julia> show(One())
just adds one

Is this a bug, or am I doing something wrong?

Base.show(io::IO, ::MIME"text/plain", f::MyAbstractFun) = println(io, representation(f))

Thanks. However, the documentation is confusing since it suggests that the two-argument show method would be sufficient (which it is, when Function is not a supertype, in which case show(io::IO, ::MIME"text/plain", ::Function) is called).

I’m not sure what is confusing. It says that you can change the behavior of show when e.g. it is in the repl by defining show for the mime type. And you inherit from a type that does this. If you didn’t want the functionality from the type, why did you inherit from it?

The confusing part is the following: the manual suggests that show(::IO, ::MyType) be used for basic custom printing, and the 3-argument show is only necessary for multi-line formats. Which is true, except when the MyType <: T and the 3-argument show is defined for T. In which case the 2-argument show is not called by display.

1 Like