Skip to content

Commit

Permalink
add NamedTuple(itr) constructor (JuliaLang#37454)
Browse files Browse the repository at this point in the history
  • Loading branch information
JeffBezanson authored Sep 9, 2020
1 parent ed2ed0c commit 26c79b2
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ New library features
--------------------

* The `redirect_*` functions can now be called on `IOContext` objects.
* New constructor `NamedTuple(iterator)` that constructs a named tuple from a key-value pair iterator.

Standard library changes
------------------------
Expand Down
11 changes: 11 additions & 0 deletions base/docs/basedocs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2393,6 +2393,17 @@ another named tuple.
"""
NamedTuple{names}(nt::NamedTuple)

"""
NamedTuple(itr)
Construct a named tuple from an iterator of key-value pairs (where the keys must be
`Symbol`s). Equivalent to `(; itr...)`.
!!! compat "Julia 1.6"
This method requires at least Julia 1.6.
"""
NamedTuple(itr)

"""
typeassert(x, type)
Expand Down
2 changes: 2 additions & 0 deletions base/namedtuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ end
NamedTuple{names, T}(itr) where {names, T <: Tuple} = NamedTuple{names, T}(T(itr))
NamedTuple{names}(itr) where {names} = NamedTuple{names}(Tuple(itr))

NamedTuple(itr) = (; itr...)

end # if Base

length(t::NamedTuple) = nfields(t)
Expand Down
2 changes: 2 additions & 0 deletions test/namedtuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ let d = [:a=>1, :b=>2, :c=>3] # use an array to preserve order
y = (w=30, z=40)
@test (;t..., y...) == (x=1, y=20, w=30, z=40)
@test (;t..., y=0, y...) == (x=1, y=0, w=30, z=40)

@test NamedTuple(d) === (a=1, b=2, c=3)
end

# inference tests
Expand Down

0 comments on commit 26c79b2

Please sign in to comment.