Skip to content

Commit

Permalink
define generic get! for AbstractDict (JuliaLang#34621)
Browse files Browse the repository at this point in the history
  • Loading branch information
bicycle1885 committed Feb 29, 2020
1 parent 4d8f889 commit c4290fe
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
8 changes: 8 additions & 0 deletions base/abstractdict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,14 @@ end
getindex(t::AbstractDict, k1, k2, ks...) = getindex(t, tuple(k1,k2,ks...))
setindex!(t::AbstractDict, v, k1, k2, ks...) = setindex!(t, v, tuple(k1,k2,ks...))

get!(t::AbstractDict, key, default) = get!(() -> default, t, key)
function get!(default::Callable, t::AbstractDict{K,V}, key) where K where V
haskey(t, key) && return t[key]
val = default()
t[key] = val
return val
end

push!(t::AbstractDict, p::Pair) = setindex!(t, p.second, p.first)
push!(t::AbstractDict, p::Pair, q::Pair) = push!(push!(t, p), q)
push!(t::AbstractDict, p::Pair, q::Pair, r::Pair...) = push!(push!(push!(t, p), q), r...)
Expand Down
2 changes: 0 additions & 2 deletions base/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -417,8 +417,6 @@ Dict{String,Int64} with 4 entries:
"""
get!(collection, key, default)

get!(h::Dict{K,V}, key0, default) where {K,V} = get!(()->default, h, key0)

"""
get!(f::Function, collection, key)
Expand Down
6 changes: 6 additions & 0 deletions test/env.jl
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ end
@test_throws KeyError ENV[key]
@test get(ENV,key,"default") == "default"
@test get(() -> "default", ENV, key) == "default"

key = randstring(25)
@test !haskey(ENV, key)
@test get!(ENV, key, "default") == "default"
@test haskey(ENV, key)
@test ENV[key] == "default"
end
@testset "#17956" begin
@test length(ENV) > 1
Expand Down

0 comments on commit c4290fe

Please sign in to comment.