Get fieldnames and values of `struct` as NamedTuple

Usually, if I have defined something like Base.length it was done as a matter of intercooperative necessity [something important would not be computable without the specialization of e.g. length to the given data type. That is my officialing.

N.B. Julia Base owns NamedTuples – I know why there is no definition of length there – I needed it in NamedTupleTools to play well with others.

N.B. Julia Base owns NamedTuples – I know why there is no definition of length there

Sure, that’s safe. We just have to make sure that other packages won’t do it, too. I would assume at least part of NamedTupleTools would be a candidate of inclusion into Base in future Julia versions anyhow, right?

That is a matter for the Community.

I think the general tendency is to move things out of Base, so I would not assume this.

That is type piracy and it typically means the package should not be used other than for interactive work and should not be used as a dependency since just loading the package can change behavior of existing code.

If certain Base methods are needed on Base types then having a discussion about adding them to Base is a good idea.

1 Like

That is type piracy …

That was my worry here, yes.

I think the general tendency is to move things out of Base , so I would not assume this.

I know. However, I think conversion between (simple) structs and tuples is something that would fit well into Base, and as @kristoffer.carlsson writes no other package outside of Base should define things like convert(::Type{NamedTuple}, ...).

FWIW

julia> x=(;a=2, b=3); @which length(x)
length(t::NamedTuple) in Base at namedtuple.jl:97

Doesn’t that work for you?

I don’t think that the NamedTuple constructor needs to be a pirate, since the user needs to spell it out anyway. It could be a different name, or a different function with the same name.

Base.convert is a problem though.

I don’t think these should exist as convert (I don’t think these should happen implicitly) but as a make_struct(::Type{MyStruct}, ::NamedTuple) or something (and at this point it isn’t type piracy of course).

2 Likes

Yes, I have something like that in the works at the moment, with functions de_struct and re_struct: https://github.com/oschulz/ArraysOfStructs.jl/blob/dev/src/namedtuple_utils.jl

1 Like

NamedTupleTools (v0.5.0) is now piracy-free.

4 Likes