Is using values() the correct way to obtain the namedtuple in keyword arguments?

Suppose I had the following method:

function character_information(name::String, age::Int32; c...)
     println("Name: $name Age: $age")
     c_values = values(c)
     println(c_values.Alignment)  
end

# We're not following D&D rules, so in my little game an intelligence
# level of 5 is considered high intelligence.
character_information("Queen Svetlana",25,Alignment="Chaotic Evil",Intelligence=5)

If I were to use typeof(c) it will return Base.Iterators.Pairs{...}. In the documentation it says:

Transforms an indexable container into an Dictionary-view of the same data.

If I were to use values(c) I would get the namedtuple that contains all the keyword-values that I passed into the function. Using a keyword(c_values.Alignment) I can access the associated value. Is that the correct way of accessing an individual value?

Values is defined to return kw.data where kw is a Pair, so in this case it does return what you want. It doesn’t need to return a NamedTuple though, that’s perhaps an implementation detail. If you specifically want a NamedTuple you might construct it by splatting as (; c...), eg.

julia> f(; kw...) = kw;

julia> kw = f(x = 1, y = 2)
pairs(::NamedTuple) with 2 entries:
  :x => 1
  :y => 2

julia> (; kw...)
(x = 1, y = 2)

Once you have a NamedTuple you may access the contents through c_values.Alignment.

However if you simply want the value assigned to the keyword argument Alignment, you might skip all this and simply use c[:Alignment]. Eg:

julia> kw = f(x = 1, y = 2)
pairs(::NamedTuple) with 2 entries:
  :x => 1
  :y => 2

julia> kw[:y]
2
1 Like