Skip to content

Commit

Permalink
Define valtype(::NamedTuple) and keytype(::NamedTuple) (#46555)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tokazama authored Jan 10, 2023
1 parent a229fbd commit 79ceb8d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
6 changes: 6 additions & 0 deletions base/namedtuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,12 @@ eltype(::Type{T}) where T<:NamedTuple = nteltype(T)
nteltype(::Type) = Any
nteltype(::Type{NamedTuple{names,T}} where names) where {T} = eltype(T)

keytype(@nospecialize nt::NamedTuple) = keytype(typeof(nt))
keytype(@nospecialize T::Type{<:NamedTuple}) = Symbol

valtype(@nospecialize nt::NamedTuple) = valtype(typeof(nt))
valtype(@nospecialize T::Type{<:NamedTuple}) = eltype(T)

==(a::NamedTuple{n}, b::NamedTuple{n}) where {n} = Tuple(a) == Tuple(b)
==(a::NamedTuple, b::NamedTuple) = false

Expand Down
3 changes: 3 additions & 0 deletions test/namedtuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ end
@test eltype(NamedTuple{(:x, :y),Tuple{Union{Missing, Int},Union{Missing, Float64}}}(
(missing, missing))) === Union{Real, Missing}

@test valtype((a=[1,2], b=[3,4])) === Vector{Int}
@test keytype((a=[1,2], b=[3,4])) === Symbol

@test Tuple((a=[1,2], b=[3,4])) == ([1,2], [3,4])
@test Tuple(NamedTuple()) === ()
@test Tuple((x=4, y=5, z=6)) == (4,5,6)
Expand Down

0 comments on commit 79ceb8d

Please sign in to comment.