Skip to content

Commit c703441

Browse files
authored
Merge pull request #70 from aplavin/np
support numeric propertynames
2 parents a756095 + 33bf7b9 commit c703441

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/ConstructionBase.jl

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,10 +71,20 @@ end
7171
end
7272
end
7373

74+
# names are consecutive integers: return tuple
75+
# names are symbols: return namedtuple
76+
# names are empty (object has no properties): also return namedtuple, for backwards compat and generally makes more sense
77+
@inline tuple_or_ntuple(names::Tuple{}, vals::Tuple) = NamedTuple{names}(vals)
78+
@inline tuple_or_ntuple(names::Tuple{Vararg{Symbol}}, vals::Tuple) = NamedTuple{names}(vals)
79+
@inline function tuple_or_ntuple(names::Tuple{Vararg{Int}}, vals::Tuple)
80+
@assert names === ntuple(identity, length(names))
81+
vals
82+
end
83+
7484
if VERSION >= v"1.7"
7585
function getproperties(obj)
7686
fnames = propertynames(obj)
77-
NamedTuple{fnames}(getproperty.(Ref(obj), fnames))
87+
tuple_or_ntuple(fnames, getproperty.(Ref(obj), fnames))
7888
end
7989
function getfields(obj::T) where {T}
8090
fnames = fieldnames(T)

test/runtests.jl

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,26 @@ Base.getproperty(obj::FieldProps, name::Symbol) = getproperty(getfield(obj, :com
298298
end
299299
end
300300
301+
302+
struct SProp
303+
names
304+
end
305+
Base.propertynames(s::SProp) = getfield(s, :names)
306+
Base.getproperty(s::SProp, prop::Symbol) = "ps$prop"
307+
Base.getproperty(s::SProp, prop::Int) = "pi$prop"
308+
Base.getproperty(s::SProp, prop::String) = "pstr$prop"
309+
310+
if VERSION >= v"1.7"
311+
# automatic getproperties() supported only on 1.7+
312+
313+
@testset "properties can be numbered" begin
314+
@test getproperties(SProp((:a, :b))) === (a="psa", b="psb")
315+
@test getproperties(SProp((1, 2))) === ("pi1", "pi2")
316+
# what should it return?
317+
@test_broken getproperties(SProp(("a", "b")))
318+
end
319+
end
320+
301321
function funny_numbers(::Type{Tuple}, n)::Tuple
302322
types = [
303323
Int128, Int16, Int32, Int64, Int8,

0 commit comments

Comments
 (0)