Skip to content

Commit

Permalink
add delete for NamedTuple
Browse files Browse the repository at this point in the history
from #27725

Co-authored-by: Jeffrey Sarnoff <JeffreySarnoff@users.noreply.github.com>
  • Loading branch information
JeffBezanson and JeffreySarnoff committed Jul 26, 2024
1 parent cdd599c commit 9d13540
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
18 changes: 18 additions & 0 deletions base/namedtuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,24 @@ function diff_fallback(a::NamedTuple, an::Tuple{Vararg{Symbol}}, bn::Tuple{Varar
_new_NamedTuple(NamedTuple{names, types}, (A...,))
end

"""
delete(a::NamedTuple, field::Symbol)
Construct a new named tuple from `a` by removing the named field.
```jldoctest
julia> Base.delete((a=1, b=2, c=3), :a)
(b = 2, c = 3)
julia> Base.delete((a=1, b=2, c=3), :b)
(a = 1, c = 3)
```
"""
@constprop :aggressive function delete(a::NamedTuple{an}, field::Symbol) where {an}
names = diff_names(an, (field,))
NamedTuple{names}(a)
end

"""
structdiff(a::NamedTuple, b::Union{NamedTuple,Type{NamedTuple}})
Expand Down
7 changes: 7 additions & 0 deletions test/namedtuple.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# This file is a part of Julia. License is MIT: https://julialang.org/license

using Base: delete

@test_throws TypeError NamedTuple{1,Tuple{}}
@test_throws TypeError NamedTuple{(),1}
@test_throws TypeError NamedTuple{(:a,1),Tuple{Int}}
Expand Down Expand Up @@ -282,6 +284,11 @@ end
abstr_nt_22194_3()
@test Base.return_types(abstr_nt_22194_3, ()) == Any[Any]

@test delete((a=1,), :a) == NamedTuple()
@test delete((a=1, b=2), :a) == (b=2,)
@test delete((a=1, b=2, c=3), :b) == (a=1, c=3)
@test delete((a=1, b=2, c=3), :z) == (a=1, b=2, c=3)

@test Base.structdiff((a=1, b=2), (b=3,)) == (a=1,)
@test Base.structdiff((a=1, b=2, z=20), (b=3,)) == (a=1, z=20)
@test Base.structdiff((a=1, b=2, z=20), (b=3, q=20, z=1)) == (a=1,)
Expand Down

0 comments on commit 9d13540

Please sign in to comment.