NamedTuple with invalid variable names

question

#1
  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.


#2

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

#3

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.


#4

I think it is totally fine.


#5

FYI a semicolon is useful for this

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

#6

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.


#7

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.


#8

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