NamedTupleTools.jl

NamedTupleTools is a small package that makes doing a few things with NamedTuples a bit easier.
(Julia v1.0)
using NamedTupleTools

julia> namedtuple(:a, :b, :c)(1, 2.0, “three”)
(a = 1, b = 2.0, c = “three”)

#=
namedtuple( name1, name2, … )
namedtuple( (name1, name2, …) )
where the names are all Symbols or all Strings

Generate a NamedTuple prototype by specifying or obtaining the fieldnames.
The prototype is applied to fieldvalues, giving a completed NamedTuple.
=#

julia> ntproto = namedtuple( :a, :b, :c )
NamedTuple{(:a, :b, :c),T} where T<:Tuple

julia> nt123 = ntproto(1, 2, 3)
(a = 1, b = 2, c = 3)

julia> ntAb3 = ntproto(“A”, “b”, 3)
(a = “A”, b = “b”, c = 3)

julia> isprototype(ntproto)
true

julia> isprototype(nt123)
false

julia> delete!(nt123, :a) === (b = 2, c = 3)
true
julia> delete!(nt123, :a, :c) === delete!(nt123, (:a, :c)) === (b = 2,)
true
julia> delete!(ntproto, :b) === namedtuple(:a, :c)
true

julia> ntproto1 = namedtuple(:a, :b);
julia> ntproto2 = namedtuple(:b, :c);

julia> merge(ntproto1,ntproto2)
NamedTuple{(:a, :b, :c),T} where T<:Tuple

Perhaps you are aware of this, but NamedTuple{(:a,:b,:c)} can also be used as a constructor, eg

julia> ntproto = NamedTuple{(:a,:b,:c)}
NamedTuple{(:a, :b, :c),T} where T<:Tuple

julia> ntproto((1, 2.0, "three"))
(a = 1, b = 2.0, c = "three")

Also, making a method for Base.delete! is

  1. type piracy,

  2. misleading, because it does not modify the argument.

2 Likes