the case
I want to be able to create a function with some default options but also without need to add full explicit list of options available for it.
And then inside I want to be able to filter from given and default options, those which are Button options or Tooltip options for example.
So something like:
Options[f] = {(*list of default options*)}
f[args__, OptionsPattern[]]:=Column[{
(*Options that are suitable for Button*),
(*Options that are suitable for Tooltip*),
OptionValue[(*specific name*)]
}]
And I wasn't able to get this with built in Options management functions: OptionsPattern[]
, OptionValue
, FilterRules
etc.
additional requirements
I want to avoid
Options[f] = Join[customOptions, Options[Button], ...]
.I don't think is a good solution, there may be duplicates in
customOptions
for them and an explicit list ofOptions[f]
grows.I want to be able to provide any option to the function without error messsage e.g.:
Unknown option Apparance for f...
We can get 2. by skipping
OptionsPattern[]
in definition but without it we can't use built inOptionValue
. I want to be able to refer to functions by their names.Rules filtering mechanism should not produce duplicates. I know
Button[..., ImageSize->300, ImageSize->200]
will behave stable but I find it ugly.
my approach
(* auxiliary functions *)
mergeRules = GatherBy[Join[##], First][[All, 1]] &;
optionValue = #2 /. # &;
(* function definition *)
ClearAll[f];
Options[f] = {"Test" -> 1, ImageSize -> 100, TooltipDelay -> 20};
f[x_, optionsPattern : (_Rule | _RuleDelayed) ...] := With[{
opt = mergeRules[{optionsPattern}, Options[f]]}
,
Column@{
FilterRules[opt, Options@Button],
FilterRules[opt, Options@Tooltip],
optionValue[opt, "Test"]
}
]
So I need to start my definitions with With[{ opt = mergeRules[ {optionsPattern}, Options[f]]}
, which does not seem to be a big problem, but why I have to do this?
tests
f[1, Appearance -> "Palette"]
{Appearance->Palette, ImageSize->100}
{TooltipDelay->20}
1
f[1, ImageSize -> 200]
{ImageSize->200}
{TooltipDelay->20}
1
f[1]
{ImageSize->100}
{TooltipDelay->20}
1
question
Is there simpler approach, with built functions maybe? Or should I include Options[Button]
etc. to Options[f]
and count on the fact that when given duplicates, first one wins?
Edits
Mr.Wizard's answer fulfills points:
1 automatically, 2/3 by using OptionsPattern[{f,Button, ...}]
. So still 4 needs custom filtering function but it is a good answer anyway.
Comments
Post a Comment