Get default function arguments

If I have a function with optional arguments like

add(a=2;b=3)=a+b

is it possible to find out what the defaults are?

I don’t think so. Default arguments just result in Julia creating extra methods for your function. For example:

julia> f(x=5) = x + 1
f (generic function with 2 methods)

julia> methods(f)
# 2 methods for generic function "f":
f() in Main at REPL[1]:1
f(x) in Main at REPL[1]:1

Defining f(x=5) = ... actually defined two methods:

f(x) = ...
f() = f(5)

so inside the inner method (f(x)), there’s no indication whether the x it received was a default argument or not. Keyword arguments do something similar by creating an inner function without keyword arguments.

What are you actually trying to do? Perhaps there’s another way.

I have a simulation with certain default parameters. Then I want to double and halve these parameters and record the results. I can do this simply by putting all the parameters in a list but I wondered if I can also do it via writing something like

add(a=defaults(add).a*2)

or something.

Ah, no, that’s not possible. After all, you could have arbitrarily many methods named add, so what would defaults(add) possibly return?

Instead, if you put your parameters in a struct and pass that struct to your function, manipulating the parameters as a group becomes much easier. Check out https://github.com/mauro3/Parameters.jl for some macros to make constructing parameter structs easier.

4 Likes