Should callers of iterate assert ::Union{Nothing,Tuple{Any,Any}}

Because callers of iterate just destructure or use indexes, all kinds of hard to understand bugs can result from incorrectly implemented iterate methods. Eg

struct Foo
    N::Int
end

function Base.iterate(foo::Foo, i = 1)
    i ≥ foo.N && return nothing
    i == 1 && return (i = 1, j = 0) # USER FORGOT , i + 1
    (i = i, j = i - 1), i + 1
end

Base.length(foo::Foo) = foo.N

collect(Foo(4))

I wonder if these could just be caught earlier, with an error that is easier to understand, if some assertions were thrown in.

Could not find an open issue, so asking here first. I would of course be happy to do a PR.

2 Likes