Subtyping NamedTuple

#1

Is it possible to subtype NamedTuple?
I unsuccessfully tried a million variations of “struct MyNamedTuple <: NamedTuple{}(); end”

0 Likes

#2

No, you can’t, in general, inherit from non abstract types!

There are lots of alternatives though, so this should be rarely needed!

1 Like

#3

You can just make a new type and put the NamedTuple inside it. Ie use composition instead of inheritance.

2 Likes

#4

I know. The reason why I wanted to avoid this solution is because I did not want an additional dot to access the internal NamedTuple.

0 Likes

#5

You can overload Base.getproperty to do direct access. E.g.

julia> let nt = Symbol("#nt")
           @eval begin
               struct MyNamedTuple{names,T}
                   $nt::NamedTuple{names,T}
               end
               Base.parent(mnt::MyNamedTuple) = getfield(mnt, $(QuoteNode(nt)))
           end
       end

julia> function Base.getproperty(mnt::MyNamedTuple, sym::Symbol)
           return getproperty(parent(mnt), sym)
       end

julia> nt = MyNamedTuple((a = 1, b = 1))
MyNamedTuple{(:a, :b),Tuple{Int64,Int64}}((a = 1, b = 1))

julia> nt.a
1
4 Likes

#6

Awesome! Thanks!

0 Likes