Skip to content

Use of variables defined inside if-else can poison inference #42996

Closed
@thchr

Description

@thchr

Consider the following function f:

function f()
    if rand(Bool)
        idxs = [[1,2],[1,2,3]]
    else
        idxs = [[1,2],[1,2,3]]
    end

    return idxs
end

As well as the functionally identical variation g:

function g()
    if rand(Bool)
        idxs = [[1,2],[1,2,3]]
    else
        idxs = [[1,2],[1,2,3]]
    end

    [idxs[j] for j in 1:length(idxs)]
    return idxs
end

Here, f will infer perfectly fine - but adding an iterator over idxs in g (which, notably, is not used for anything) will cause inference to give up, inferring Any as return value. Effectively, using the iterator poisons everything.

Defining and using variables this way is definitely an anti-pattern (and can be avoided in several ways) but sincef works just fine (and e.g., is not disallowed) it struck me as unintended that g does not.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions