Named tuples - construction, unpacking

I stumbled by accident upon the fact that you can create a named tuple by naming one or more of the elements, not all of them. At least, it seems, as long as the un-named elements are given by existing variables:

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

julia> foo = (a, b) # regular tuple
(1, 2)

julia> bar = (a=a, b) # only named first element
(a = 1, b = 2)

julia> baz = (a, b=b) # only named second element
(a = 1, b = 2)

julia> qux = (a=3, b) # values don't have to be variables
(a = 3, b = 2)

I don’t see this behavior mentioned in the docs.

Also tangentially related: I was wondering if there’s a technique to tersely “unpack” a named tuple into a local scope without having to explicitly name the variables being unpacked into. I’m thinking of (ab)using named tuples as kind of anonymous, implicitly-defined struct instances that can be used to carry related values around, and easily use the contained values by name without having to use dot syntax (for clarity) nor explicitly unpack into named variables (to avoid effectively having to repeat the definition of the named tuple and be robust to ordering of its elements, etc).

… turns out, as often is the case, that someone has already created a package that does almost nearly that! UnPack.jl. The only thing it can’t do is let me just unpack the entire named tuple but I take it from another discussion that that is probably not possible anyway:

… actually, I take it back, it seems there is a way:

This does pretty much exactly what I wanted!

big_named_tuple_full_of_stuff = (important_var1=42, important_var2=999, irrelevant=-1)

@with big_named_tuple_full_of_stuff begin
  result = &important_var1 + &importantvar_2
end

:slightly_smiling_face:

4 Likes

You can create named tuple by naming none of the elements, by using a semicolon:

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

julia> (a,b)
(1, 2)

julia> (;a, b)
(a = 1, b = 2)

This is documented in ?NamedTuple.

5 Likes

Nice! I had only looked at Functions · The Julia Language, didn’t think to search in the docs for NamedTuple.

1 Like