1
$\begingroup$

Say I have two functions which take the same set of options, e.g.

Options[f1] = {a -> 1};
Options[f2] = {a -> 1};

Now, f1 calls f2 and passes its options on, like this:

f1[options:OptionsPattern[]] := f2[options]

Where f2 may be

f2[options:OptionsPattern[]] := OptionValue[a]

Usually ,this works fine:

f1[]
(* 1 *)

f1[a -> 2]
(* 2 *)

But SetOptions does not behave the way I want it to:

SetOptions[f1, a -> 2];
f1[]
(* 1 *)

I understand that this does not work because options is empty, and f2 never asks for the Options of f1. One way to solve this is to define

f2[options:OptionsPattern[]] :=  If[
  Length[{options}] > 0, 
  OptionValue[a], 
  OptionValue[f1, a]
]

Now, after SetOptions[f1, a -> 2]

f1[]
(* 2 *)

f1[a -> 3]
(* 3 *)

Is there a better way to do this?

$\endgroup$
  • 1
    $\begingroup$ See this $\endgroup$ – b3m2a1 Jul 16 '17 at 0:26