Skip to content

Commit

Permalink
make keytype and valtype work for UnionAll AbstractDicts (#53116
Browse files Browse the repository at this point in the history
)

Fixes #53115
  • Loading branch information
nsajko authored Jan 30, 2024
1 parent ef69db6 commit fdb342c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
4 changes: 2 additions & 2 deletions base/abstractdict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ julia> keytype(Dict(Int32(1) => "foo"))
Int32
```
"""
keytype(::Type{<:AbstractDict{K,V}}) where {K,V} = K
keytype(::Type{<:AbstractDict{K}}) where {K} = K
keytype(a::AbstractDict) = keytype(typeof(a))

"""
Expand All @@ -315,7 +315,7 @@ julia> valtype(Dict(Int32(1) => "foo"))
String
```
"""
valtype(::Type{<:AbstractDict{K,V}}) where {K,V} = V
valtype(::Type{<:AbstractDict{<:Any,V}}) where {V} = V
valtype(a::AbstractDict) = valtype(typeof(a))

"""
Expand Down
21 changes: 21 additions & 0 deletions test/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1519,3 +1519,24 @@ let d = Dict()
d[1.0] = 'b'
@test only(d) === Pair{Any,Any}(1.0, 'b')
end

@testset "UnionAll `keytype` and `valtype` (issue #53115)" begin
K = Int8
V = Int16
dicts = (
AbstractDict, IdDict, Dict, WeakKeyDict, Base.ImmutableDict,
Base.PersistentDict, Iterators.Pairs
)

@testset "D: $D" for D dicts
@test_throws MethodError keytype(D)
@test_throws MethodError keytype(D{<:Any,V})
@test keytype(D{K }) == K
@test keytype(D{K, V}) == K

@test_throws MethodError valtype(D)
@test valtype(D{<:Any,V}) == V
@test_throws MethodError valtype(D{K })
@test valtype(D{K, V}) == V
end
end

0 comments on commit fdb342c

Please sign in to comment.