Skip to content

minimum implementation for type wrapping a NamedTuple #214

Description

@tpapp

I have a type wrapping a NamedTuple, that essentially forwards getproperty. For the purposes of the MWE, let it be

struct WrapNT{NT<:NamedTuple}
    nt::NT
    count::Int # for the purposes of the MWE, maintain as length(nt)
end

@inline _nt(wnt::WrapNT) = getfield(wnt, :nt) # save typing

Base.show(io::IO, wnt::WrapNT) = print(getfield(wnt, :count), " fields ", _nt(wnt))

# constructor
wrap_NT(nt::NamedTuple) = WrapNT(nt, length(nt))

Base.propertynames(wnt::WrapNT) = propertynames(_nt(wnt))

Base.getproperty(wnt::WrapNT, sym::Symbol) = getproperty(_nt(wnt), sym)

The question is: how should I hook into the API of Accessors.jl so that stuff "just works"? I experimented and found that

function Accessors.insert(wnt::WrapNT, lens::PropertyLens{S}, val) where S
    wrap_NT(Accessors.insert(_nt(wnt), lens, val))
end

function Accessors.set(wnt::WrapNT, lens::PropertyLens{S}, val) where S
    wrap_NT(Accessors.set(_nt(wnt), lens, val))
end

function Accessors.delete(wnt::WrapNT, lens::PropertyLens{S}) where S
    wrap_NT(Accessors.delete(_nt(wnt), lens))
end

works, but from the manual it is not clear if this is enough.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions