Reputation: 117
I'm quite new to Julia and I'm looking into porting some Python code to Julia. This code uses __repr__() overloading to display cutsom types. I understand that Julia provides the string() method for this functionality. But I can't figure it out.
julia> type Thomas
t::Integer
end
julia> function Base.string(t::Thomas)
"---> $(t.t) <---"
end
julia> r = Thomas(8);
With these definitions I expected my string(::Thomas) function to be called whenever a value of type Thomas needed to be converted to a string. In one case, it works as expected:
julia> println("$r")
---> 8 <---
But, for the most cases it does not:
julia> println(r)
Thomas(8)
julia> println(" $r")
Thomas(8)
julia> println("r = $r")
r = Thomas(8)
julia> repr(r)
"Thomas(8)"
What did I get wrong ? Is there some other function I should define for my new custom type ?
I am running Julia 0.4.0-dev. (the code above was pasted from the REPL of Version 0.4.0-dev+3607 (2015-02-26 07:41 UTC), Commit bef6bf3*, x86_64-linux-gnu)
Upvotes: 3
Views: 972
Reputation: 5325
At the moment just overriding Base.show
should be enough, as follows.
type Thomas
t::Int # note Int not Integer
end
Base.show(io::IO, x::Thomas) = print(io, "Thomas with $(x.t)")
Note that in the definition of the type, you should use the concrete type Int
(equivalent to Int64
or Int32
, depending on your machine's word size), not the abstract type Integer
, which will lead to bad performance.
The situation with Base.show
, Base.print
etc. is indeed confusing at the moment, but with some recent work (look up IOContext
) should get simplified and clarified soon.
Upvotes: 6
Reputation: 364
You have to override two versions of Base.print actually to get a consistent behavior of string interpolation:
Base.print(io::IOBuffer, t::Thomas) = Base.print(io, "---> $(t.t) <---")
Base.print(t::Thomas) = Base.print("---> $(t.t) <---")
Then you'll have:
print(t)
string(t)
string(t, t, ...)
"$t"
"t = $t"
"$t $t $t"
and co.
Upvotes: 2
Reputation: 32381
You may want to override the show
method as well.
Base.show(io::IO, x::Thomas) = show(io, string(x))
Upvotes: 1