Skip to content

Commit a2f56bc

Browse files
author
KristofferC
committed
print NamedTuple types using the macro format
1 parent 703b3f8 commit a2f56bc

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

base/show.jl

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1060,11 +1060,12 @@ end
10601060
function show_datatype(io::IO, x::DataType, wheres::Vector{TypeVar}=TypeVar[])
10611061
parameters = x.parameters::SimpleVector
10621062
istuple = x.name === Tuple.name
1063+
isnamedtuple = x.name === typename(NamedTuple)
10631064
n = length(parameters)
10641065

10651066
# Print tuple types with homogeneous tails longer than max_n compactly using `NTuple` or `Vararg`
1066-
max_n = 3
10671067
if istuple
1068+
max_n = 3
10681069
taillen = 1
10691070
for i in (n-1):-1:1
10701071
if parameters[i] === parameters[n]
@@ -1090,6 +1091,20 @@ function show_datatype(io::IO, x::DataType, wheres::Vector{TypeVar}=TypeVar[])
10901091
end
10911092
print(io, "}")
10921093
end
1094+
elseif isnamedtuple
1095+
print(io, "@NamedTuple{")
1096+
syms, types = parameters
1097+
first = true
1098+
for i in 1:length(syms)
1099+
if !first
1100+
print(io, ", ")
1101+
end
1102+
print(io, syms[i])
1103+
print(io, "::")
1104+
show(io, types.parameters[i])
1105+
first = false
1106+
end
1107+
print(io, "}")
10931108
else
10941109
show_type_name(io, x.name)
10951110
show_typeparams(io, parameters, (unwrap_unionall(x.name.wrapper)::DataType).parameters, wheres)

test/show.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1348,6 +1348,12 @@ test_repr("(:).a")
13481348
@test repr(Tuple{String, Int64, Int64, Int64}) == "Tuple{String, Int64, Int64, Int64}"
13491349
@test repr(Tuple{String, Int64, Int64, Int64, Int64}) == "Tuple{String, Vararg{Int64, 4}}"
13501350

1351+
# Test printing of NamedTuples using the macro syntax
1352+
@test repr(@NamedTuple{kw::Int64}) == "@NamedTuple{kw::Int64}"
1353+
@test repr(@NamedTuple{kw::Union{Float64, Int64}, kw2::Int64}) == "@NamedTuple{kw::Union{Float64, Int64}, kw2::Int64}"
1354+
@test repr(@NamedTuple{kw::@NamedTuple{kw2::Int64}}) == "@NamedTuple{kw::@NamedTuple{kw2::Int64}}"
1355+
@test repr(@NamedTuple{kw::NTuple{7, Int64}}) == "@NamedTuple{kw::NTuple{7, Int64}}"
1356+
13511357
@testset "issue #42931" begin
13521358
@test repr(NTuple{4, :A}) == "NTuple{4, :A}"
13531359
@test repr(NTuple{3, :A}) == "Tuple{:A, :A, :A}"

0 commit comments

Comments
 (0)