Subtyping NamedTuple

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

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

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

2 Likes

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.

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
5 Likes

Awesome! Thanks!