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

Consider adding an attrs-like converter macro? #100

Closed
singularitti opened this issue Jul 24, 2019 · 1 comment
Closed

Consider adding an attrs-like converter macro? #100

singularitti opened this issue Jul 24, 2019 · 1 comment

Comments

@singularitti
Copy link
Contributor

I was using attrs in Python. It shares a similar functionality as Parameters.jl. However, one thing it has is not supported by Parameters.jl now---the default converter. It is often the case that users do not supply the right type of parameters to the constructor. I want that we can handle this if they do not give the right type instead of throwing an error.
Here is an example:

struct A
   mass::Int
   velocity::String
   coordinate::Vector{Pair{Int, Float64}}
   time::NTuple{3, Float64}
   frequency::Float64
end

For some reason, I want to handle if a user supplies a Vector{Float64} or a NTuple{N,Float64} to the coordinate field, the construct A could directly converts it to a Vector{Pair{Int, Float64}}, by calling a function

convertfield(x::Vector{Pair{Int, Float64}}) = x
function convertfield(x::Union{AbstractVector{<: Real}, NTuple{N, <: Real} where {N}})
    return collect(pairs(Float64.(x)))
end

on it. The syntax could be like

@with_kw struct A
   mass::Int
   velocity::String
   coordinate::Vector{Pair{Int, Float64}} = ones(3); @convert convertfiled(coordinate); @assert length(coordinate) == 3
   time::NTuple{3, Float64}
   frequency::Float64
end

where @convert is a macro that takes a function. I could write something like

@with_kw struct A
   mass::Int
   velocity::String
   coordinate::Vector{Pair{Int, Float64}} = collect(pairs(ones(3)))
   time::NTuple{3, Float64}
   frequency::Float64
end

But it is just a default value, not a converter.

@singularitti singularitti changed the title Consider giving an attrs-like default converter? Consider adding an attrs-like converter macro? Jul 24, 2019
@mauro3
Copy link
Owner

mauro3 commented Nov 23, 2019

I am not really interested in supporting this as it is too much of a feature creep to me.

Maybe some sort of plug-in system should be made, so you can do this personally. Not sure what this could look like.

@mauro3 mauro3 closed this as completed Nov 23, 2019
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

No branches or pull requests

2 participants