Julia: Showing array of user types with overloaded Base.show

Created on 29 Jul 2014  路  5Comments  路  Source: JuliaLang/julia

If I overload Base.show for my user type, when I display an array of my user type it calls my Base.show function three times for each element.

julia> type MyType
p1
end

julia> import Base.show
julia> function show(io::IO,m::MyType)
print("MyType\np1 = ",m.p1);
end

julia> a = MyType(5)
MyType
p1 = 5

julia> [a]
1-element Array{MyType,1}:
MyType
p1 = 5 MyType
p1 = 5MyType
p1 = 5

julia> b = MyType(6)
MyType
p1 = 6

julia> [a,b]
2-element Array{MyType,1}:
MyType
p1 = 5MyType
p1 = 6 MyType
p1 = 5MyType
p1 = 5
 MyType
p1 = 6MyType
p1 = 6

I've tried things like overloading Base.showcompact, Base.print_matrix, Base.showarray, Base.display.
I've also tried defining a Base.show(io::IO,mVec::Vector{MyType}) method. It always just calls Base.show three times for each element. Is there a clean way to do show user type arrays?

Most helpful comment

@JeffBezanson : Logically it would make sense to show each element once. Showing it multiple times makes the output cluttered and hard to understand.

@ivarne :+1: holy crap, I think you nailed it. It's working now, I think this issue can be closed. Thanks!

All 5 comments

Why exactly is it a problem that it calls your show method 3 times for each element?

You will probably want the print statement to have io as the first parameter to print

Ah yes, @ivarne is quite right: the reason io is passed to show is for you to write your output to it.

@JeffBezanson : Logically it would make sense to show each element once. Showing it multiple times makes the output cluttered and hard to understand.

@ivarne :+1: holy crap, I think you nailed it. It's working now, I think this issue can be closed. Thanks!

The values are printed multiple times in order to figure out how to do the output alignment and truncation. I suppose this could be an issue for a type that was very expensive to print but I've yet to encounter such a case.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

iamed2 picture iamed2  路  3Comments

helgee picture helgee  路  3Comments

m-j-w picture m-j-w  路  3Comments

wilburtownsend picture wilburtownsend  路  3Comments

StefanKarpinski picture StefanKarpinski  路  3Comments