Skip to content

inference fails for a NamedTuple with one field, but succeeds for larger named tuples #56387

Closed
@nsajko

Description

@nsajko

Reproducer:

function get_field_type(::Type{T}, field::Symbol) where {T <: NamedTuple}
    names = fieldnames(T)
    types = fieldtypes(T)
    index = findfirst(==(field), names) 
    if index === nothing
        throw(ArgumentError("Field $field not found"))
    end
    types[index]
end

function get_field_type(nt::NamedTuple, field::Symbol)
    get_field_type(typeof(nt), field) 
end

function f(nt)
    get_field_type(nt, :a)
end

Core.Compiler.return_type(f, Tuple{typeof((; a = 1))})         # inference fails: `DataType`
Core.Compiler.return_type(f, Tuple{typeof((; a = 1, b = 2))})  # OK: `Type{Int64}`

This comes from Discourse: https://discourse.julialang.org/t/constant-propagation-with-a-namedtuple-with-one-field/121887

Both return types were inferred as Type{Int64} back in v1.9.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions