NamedTuple with invalid variable names


  1. Are NamedTuples with keys which are not valid variable names allowed? eg

    julia> NamedTuple{(Symbol("1"), )}(19)
    (1 = 19,)

    they seem to work in 1.*, so possibly yes, but I am wondering if it is OK to rely on this.

  2. Is there an easier syntax for them than the above?

I am asking because I am working on a package that would return column data with an iterator that yields NamedTuples, and it would be awkward not to handle weird column names.


doesn’t work that well:

julia-1.0> t = NamedTuple{(Symbol("1"), )}(19)
(1 = 19,)

julia-1.0> t.1
ERROR: syntax: extra token "0.1" after end of expression


It is still accessible by t[Symbol("1")].

Just to clarify, the question is not about whether this is convenient, as it isn’t. I am asking whether it is part of the design, or just works accidentally.


I think it is totally fine.


FYI a semicolon is useful for this

julia> (; :function => 1, Symbol("1") => 2)
(function = 1, 1 = 2)


Null is forbidden, though:

julia> Symbol("a\0b")
ERROR: ArgumentError: Symbol name may not contain \0

And at least the REPL makes assumptions about symbols being valid encoded strings.

julia> s=rand(UInt8, 20) |> String |>Symbol;

julia> s
Error showing value of type Symbol:
ERROR: Base.InvalidCharError{Char}('\x83')

So I’d be mildly cautious before using Symbol for binary blobs.


Thanks, but they are not binary blobs but columns names (eg the first row in a CSV file). I think that in this context it is fair to say that if someone wants to put a \0 in a variable name, they should reflect on the wisdom of this choice.


I agree with the assessment that this is allowable, just inconvenient. As long as there are no embedded nul characters it should be fine.