Short Names for Keyword Arguments

Can I alias keyword arguments for brevity?

For example, in MATLAB I can do the following

x = linspace(0, 1);
y = x.^2;
lw = "linewidth"

close all
plot(x, y, lw=2)

There is a similar thing in python’s matplotlib where keyword arguments have short names.

Is this possible in Julia?

I tried both of the following in CairoMakie but neither worked.

using LinearAlgebra, CairoMakie

x = LinRange(0, 1, 100)
y = x.^2

# Neither of the following work
#lw = "linewidth" 
#lw = :linewidth

fig, ax, ln = lines([x y])
# fig, ax, ln = lines([x y]; lw=3)

I don’t believe there is anything like this, no.

If it helps at all, you can make a NamedTuple or Dict to splat for keywords. I often find this nice for plotting and other functions that use a large number of keywords, especially when I need to pass the same options to multiple function calls.

plotkws = (;linewidth=3, color="red") # NamedTuple for keyword arguments
# plotkws = Dict(:linewidth=>3, :color=>"red") # Dict for keyword arguments

fig, ax, ln = lines([x y]; plotkws...)

# NOTE: duplicate keywords are overwritten with the right-most value
fig, ax, ln = lines([x y]; plotkws..., color="blue") # same as above but set new color

You can implement it yourself.
Plots.jl does this.
I assume it does it through some normalization function that maps all the different keywords a common name and choses the last of them to use the value from.

1 Like

That’s on the implementation side. But on the caller-side you can do exactly what @TI36XPro asks, even if the given function hasn’t implemented short aliases itself. You just use a Pair (with =>) instead of a kwarg literal:

x = LinRange(0, 1, 100)
y = x.^2
lw = :linewidth
fig, ax, ln = lines([x y]; lw=>3)
11 Likes