Skip to content

Commit

Permalink
Merge pull request #12453 from rened/dict
Browse files Browse the repository at this point in the history
fix #12451 by providing a better error message
  • Loading branch information
StefanKarpinski committed Aug 12, 2015
2 parents 963ab22 + 79db1ac commit 90fe14d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
14 changes: 13 additions & 1 deletion base/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,19 @@ Dict{K }(ps::Pair{K}...,) = Dict{K,Any}(ps)
Dict{V }(ps::Pair{TypeVar(:K),V}...,) = Dict{Any,V}(ps)
Dict( ps::Pair...) = Dict{Any,Any}(ps)

Dict(kv) = dict_with_eltype(kv, eltype(kv))
function Dict(kv)
try
Base.dict_with_eltype(kv, eltype(kv))
catch e
if any(x->isempty(methods(x, (typeof(kv),))), [start, next, done]) ||
!all(x->isa(x,Union{Tuple,Pair}),kv)
throw(ArgumentError("Dict(kv): kv needs to be an iterator of tuples or pairs"))
else
rethrow(e)
end
end
end

This comment has been minimized.

Copy link
@carnaval

carnaval Aug 12, 2015

Contributor

this strikes me as rather inelegant. It should also be cheaper to simply check for isa(x,Union{Tuple,Pair}) in the iteration loop since this kind of branch should be removed when specialized on iterators that provably give tuple or pairs. The try block is treated pessimistically everywhere.

This comment has been minimized.

Copy link
@StefanKarpinski

StefanKarpinski Aug 12, 2015

Author Member

Great. Please make a PR to improve.

dict_with_eltype{K,V}(kv, ::Type{Tuple{K,V}}) = Dict{K,V}(kv)
dict_with_eltype{K,V}(kv, ::Type{Pair{K,V}}) = Dict{K,V}(kv)
dict_with_eltype(kv, t) = Dict{Any,Any}(kv)
Expand Down
6 changes: 6 additions & 0 deletions test/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -338,3 +338,9 @@ end
d = Dict('a'=>1, 'b'=>1, 'c'=> 3)
@test [d[k] for k in keys(d)] == [d[k] for k in eachindex(d)] ==
[v for (k, v) in d] == [d[x[1]] for (i, x) in enumerate(d)]


# Issue 12451
@test_throws ArgumentError Dict(0)
@test_throws ArgumentError Dict([1])
@test_throws ArgumentError Dict([(1,2),0])

0 comments on commit 90fe14d

Please sign in to comment.