Types with default field values, keyword constructors and (un-)pack macros
OTHER License
This is a package I use to handle numerical-model parameters, thus the name. However, it should be useful otherwise too. It has two main features:
struct
s and NamedTuples
,Checkout my ten minute JuliaCon 2018 talk.
The macro @with_kw
which decorates a type definition to
allow default values and a keyword constructor:
julia> using Parameters
julia> @with_kw struct A
a::Int = 6
b::Float64 = -1.1
c::UInt8
end
julia> A(c=4)
A
a: 6
b: -1.1
c: 4
julia> A()
ERROR: Field 'c' has no default, supply it with keyword.
julia> A(c=4, a = 2)
A
a: 2
b: -1.1
c: 4
The macro also supports constructors for named tuples with default values; e.g.
julia> MyNT = @with_kw (x = 1, y = "foo", z = :(bar))
(::#5) (generic function with 2 methods)
julia> MyNT()
(x = 1, y = "foo", z = :bar)
julia> MyNT(x = 2)
(x = 2, y = "foo", z = :bar)
Unpacking is done with @unpack
(@pack!
is similar):
struct B
a
b
c
end
@unpack a, c = B(4,5,6)
# is equivalent to
BB = B(4,5,6)
a = BB.a
c = BB.c
Defining several constants
@consts begin
a = 1
b = 2.0
c = "a"
end
The features are:
@unpack_*
where *
is@pack!
, @unpack
(work with@consts
macro to defined a bunch of constantsThe keyword-constructor and default-values functionality will probably make it into Julia (# 10146, #533 and #6122) although probably not with all the features present in this package. I suspect that this package should stay usable & useful even after this change lands in Julia. Note that keyword functions are currently slow in Julia, so these constructors should not be used in hot inner loops. However, the normal positional constructor is also provided and could be used in performance critical code.
NEWS.md keeps tabs on updates.
Documentation is here: stable and latest.
Complementary:
Implementing similar things:
Base.@kwdef
has functionality similar to @with_kw
but more@unpack
functionality.