Function Repository Resource:

InheritOptions

Source Notebook

Pass options down from one function into the next when the default option values are different

Contributed by: Sjoerd Smit

ResourceFunction["InheritOptions"][fg]

creates a list of options for g from options entered into f, taking account the fact that f might have different default option values.

ResourceFunction["InheritOptions"][fg,opts]

uses options opts instead of the defaults.

ResourceFunction["InheritOptions"][fg,assoc]

treats an Association as an option specification.

Details

ResourceFunction["InheritOptions"] is an alternative to FilterRules that can be used when the main function has different default option values than the function that the options are passed on to.

Examples

Basic Examples (2) 

Create option rules for a function g, assuming that it was called from f and should use those default values where possible:

In[1]:=
Options[f] = {"a" -> 1, "b" -> 2};
Options[g] = {"a" -> 3};
ResourceFunction["InheritOptions"][f -> g]
Out[3]=

Explicit options will override the defaults and only options valid for g will be passed down:

In[4]:=
ResourceFunction["InheritOptions"][f -> g, {"a" -> 5, "b" -> 6}]
Out[4]=

Scope (3) 

InheritOptions will work with any option specification after the first argument. A Sequence of rules:

In[5]:=
ResourceFunction["InheritOptions"][Graphics -> Image, ImageSize -> 100, BaselinePosition -> Bottom]
Out[5]=

A list of rules:

In[6]:=
ResourceFunction["InheritOptions"][
 Graphics -> Image, {ImageSize -> 100, BaselinePosition -> Bottom}]
Out[6]=

Specifying options as an Association is also supported:

In[7]:=
ResourceFunction["InheritOptions"][
 Graphics -> Image, <|ImageSize -> 100, BaselinePosition -> Bottom|>]
Out[7]=

Properties and Relations (3) 

Normally, FilterRules is used to pass options down to a lower function:

In[8]:=
ClearAll[f, g]
Options[f] = {"a" -> 1, "b" -> 2};
Options[g] = {"a" -> 1};
f[opts : OptionsPattern[]] := {
   g[FilterRules[{opts}, Options[g]]], OptionValue["b"]
   };
g[OptionsPattern[]] := OptionValue["a"];
In[9]:=
{f[], f["a" -> 5, "b" -> 10]}
Out[9]=

However, if the defaults of f change, this will not actually change the default behavior of f since the default for g still gets used:

In[10]:=
SetOptions[f, "a" -> 10]
Out[10]=
In[11]:=
f[]
Out[11]=

InheritOptions will always use the default values of the main function:

In[12]:=
ClearAll[h]
Options[h] = {"a" -> 1, "b" -> 2};
h[opts : OptionsPattern[]] := {
   g[ResourceFunction["InheritOptions"][h -> g, opts]], OptionValue["b"]
   };
h[]
Out[15]=
In[16]:=
SetOptions[h, "a" -> 10];
h[]
Out[17]=

Publisher

Sjoerd Smit

Requirements

Wolfram Language 13.0 (December 2021) or above

Version History

  • 1.0.0 – 10 April 2023

License Information