Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Actually use properties, not fields #59

Closed
aplavin opened this issue Jun 22, 2022 · 1 comment · Fixed by #60
Closed

Actually use properties, not fields #59

aplavin opened this issue Jun 22, 2022 · 1 comment · Fixed by #60

Comments

@aplavin
Copy link
Member

aplavin commented Jun 22, 2022

Both getproperties and setproperties are documented to relate to struct properties and not its fields.
However, the implementation is very inconsistent in fields vs properties.
Calling fieldnames and then getproperties:

fnames = fieldnames(obj)
fvals = map(fnames) do fname
Expr(:call, :getproperty, :obj, QuoteNode(fname))

Reporting fieldnames in the error message:
Failed to assign properties $(fieldnames(P)) to object with fields $(fieldnames(O)).

These inconsistencies lead to confusing errors, e.g.:

julia> using ConstructionBase, StructArrays

julia> s = StructArray(a=1:5)
5-element StructArray(::UnitRange{Int64}) with eltype NamedTuple{(:a,), Tuple{Int64}}:
 (a = 1,)
 (a = 2,)
 (a = 3,)
 (a = 4,)
 (a = 5,)

julia> fieldnames(typeof(s))
(:components,)

julia> propertynames(s)
(:a,)

julia> getproperties(s)
ERROR: type NamedTuple has no field components
# ConstructionBase tries to call getproperty(s, :components) which clearly doesn't exist

Maybe, getproperties

@generated function getproperties(obj)
fnames = fieldnames(obj)
fvals = map(fnames) do fname
Expr(:call, :getproperty, :obj, QuoteNode(fname))
end
fvals = Expr(:tuple, fvals...)
:(NamedTuple{$fnames}($fvals))
end

can be replaced with

@inline function getproperties(obj)
    fnames = propertynames(obj)
    NamedTuple{fnames}(getproperty.(Ref(obj), fnames))
end

? It infers just fine on 1.7+.

@jw3126
Copy link
Member

jw3126 commented Jun 22, 2022

Wow nice! We would love to get rid of fieldnames usage as much as possible. I tried quite a bit in the past, but mostly failed. If your suggestions passes the test suite (on 1.7+), that would be awesome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants