Named tuples

I am experimenting with named tuples to store my parameters for code readability. I have noticed that although one can create a tuple with one element, it cannot be accessed via the dot notation:

a = (b=3)

returns

julia> a.b
ERROR: type Int64 has no field b
Stacktrace:
 [1] getproperty(::Int64, ::Symbol) at ./Base.jl:33

On the other hand, a tuple with two elements:

a = (b=3, c=4)

handles perfectly fine:

a.b

returns 3 as expected.

Is this expected behavior? What is the rationale? In general, I might wish to store parameters in a named tuple (perhaps a named array in the future), and at times, there might only be a single parameter.

Thanks.

The syntax for tuple creation requires at least one comma, otherwise the parantheses are just used for precedence:
(b=3,)

6 Likes

To expand on this answer:

julia> a = (b=3)
3

julia> typeof(a)
Int64

julia> a = (b=3,)
(b = 3,)

julia> typeof(a)
NamedTuple{(:b,),Tuple{Int64}}

julia> a.b
3
1 Like

I was taught (in Python, but it applies here too) to think of the comma as the tuple operator, not the parentheses. I’ve found that lesson helpful in cases like this.

3 Likes

Thank you all! Regarding use of the comma:

a = 3,

does not work as intended. One has to use

a = (3,)

But that is hardly an issue.

You need both, otherwise how would you distinguish between

a = (3,)

and

(a = 3,)

?

3 Likes

For tuples you can write tuple(3) if you think the comma is too subtle, it’s a pity that tuple(a = 3) doesn’t make a named tuple.