Get simple name of type in Julia?
Asked Answered
M

2

9

Say I have

struct MyStruct{T,U}
  a::T
  b::U
end

I'd like to define a custom show which eliminates a lot of noise from the full type.

E.g. if I create the following:

z = MyStruct((a=1,b=2),rand(5))

then typeof shows much more than I want:

julia> typeof(z)
MyStruct{NamedTuple{(:a, :b), Tuple{Int64, Int64}}, Vector{Float64}}

How can I programmatically get just MyStruct from z into a string?

Marozas answered 20/11, 2021 at 4:49 Comment(1)
The typeof result is very long because that's the concrete type of the instance z. MyStruct is an abstract type, specifically an iterated union (UnionAll) of types with varying parameters T,U. That may be fine for printing purposes, but just be aware that when z and z2 both print MyStruct, it's very possible that typeof(z) != typeof(z2).Atonic
A
12

Some lengthy discussions on Discourse here and here, which provide at least these two solutions (the second one generalising the first):

julia> Base.typename(typeof(z)).wrapper
MyStruct

julia> name(::Type{T}) where {T} = (isempty(T.parameters) ? T : T.name.wrapper)
name (generic function with 1 method)

julia> name(typeof(z))
MyStruct
Amena answered 20/11, 2021 at 6:33 Comment(0)
W
1

If you only need a string/symbol representation, you could use:

julia> nameof(Array{Int64, 1}
:Array

julia>nameof(typeof(z))
:MyStruct
Waddell answered 30/5, 2023 at 9:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.