I had hoped that indexing a named tuple (#22194) with a Symbol
would be a type-inferrable operation. I'm guessing that a tfunc or whatever, like for Tuple
, may be needed here.
_ _ _(_)_ | A fresh approach to technical computing
(_) | (_) (_) | Documentation: https://docs.julialang.org
_ _ _| |_ __ _ | Type "?help" for help.
| | | | | | |/ _` | |
| | |_| | | | (_| | | Version 0.7.0-DEV.2400 (2017-11-02 03:12 UTC)
_/ |\__'_|_|_|\__'_| | ajf/empty/5fa163f (fork: 1 commits, 0 days)
|__/ | x86_64-linux-gnu
julia> nt = (a=1, b=2.0)
(a = 1, b = 2.0)
julia> f(x) = x[:a]
f (generic function with 1 method)
julia> @code_warntype f(nt)
Variables:
x::NamedTuple{(:a, :b),Tuple{Int64,Float64}}
Body:
begin
return (Base.getfield)(x::NamedTuple{(:a, :b),Tuple{Int64,Float64}}, :a)::Union{Float64, Int64}
end::Union{Float64, Int64}
@vtjnash, I believe you've done some constant prop work that might soon help here?
That would be even better :) I changed the OP to wrap in a function to ~better~ actually reflect the problem.
That's the only way this could work. Note that the nt.a
form is type inferred:
julia> f(x) = x.a
f (generic function with 1 method)
julia> @code_warntype f(nt)
Variables:
x::NamedTuple{(:a, :b),Tuple{Int64,Float64}}
Body:
begin
return (Core.getfield)(x::NamedTuple{(:a, :b),Tuple{Int64,Float64}}, :a)::Int64
end::Int64
You can usually get around constant propagation issues by wrapping things in a type. So Val{:a}()
or Field{:a}()
ala https://github.com/JuliaLang/julia/issues/1974#issuecomment-286961466 could avoid this issue. One reason why having a nice syntax for Field{:a}()
would be nice, like .a
. Alternatively @pure
annotations seem to help.
Yes, you can definitely work around this in a variety of ways - it's just that intuitively we can use getindex
on a tuple so why not a named tuple?
Duplicate of #24011
See PR #24362
Most helpful comment
See PR #24362