7
$\begingroup$

The documentation on OptionsPattern leaves me with some unanswered questions. From the example section:

Options[f] = {a -> a0, b -> b0}; 

f[x_, OptionsPattern[]] := {x, OptionValue[a]}

f[7, a -> uuu]
(* {7, uuu} *)

I don't think using global symbols for the named Options is a great idea so I wonder how to localise them / make sure there isn't going to be any conflict with other definitions in the same document?

a=1;
f[7, a -> uuu]
(* {f[7, 1 -> uuu], a0} *)
$\endgroup$
1
  • 1
    $\begingroup$ A somehwat relevant discussion. Since that post, I have changed my views a little, now I use strings as option names somewhat more often than before. $\endgroup$ – Leonid Shifrin Jan 27 '15 at 17:21
11
$\begingroup$

Some built-in functions use strings as option names:

Options[f] = {"AnObscureOption" -> 1};
f[x_, OptionsPattern[]] := {x, OptionValue["AnObscureOption"]}

Advantages of this are that the global namespace is not cluttered with extra symbols and they do not have to be write protected but there is a disadvantage in that they are not amenable to usage type documentation:

"AnObscureOption"::usage = "\"AnObscureOption\" is an obscure option for function f.";

Message::name: Message name "AnObscureOption"::usage is not of the form symbol::name or symbol::name::language.

$\endgroup$
3
  • 1
    $\begingroup$ Just seen @tchronis's answer -- must type faster! Guess I'll leave mine for now as I mention a disadvantage of string option names. $\endgroup$ – MikeLimaOscar Jan 27 '15 at 14:52
  • $\begingroup$ You are very welcome @MikeLimaOscar. Indeed strings cannot have a usage. $\endgroup$ – tchronis Jan 27 '15 at 14:56
  • $\begingroup$ Bigger disadvantage for me is that I can't use auto-completion with them. (But yes, I also use strings.) $\endgroup$ – Szabolcs Jan 27 '15 at 15:47
8
$\begingroup$

It is normal for option variables to be global and to be given the property Protected, which will prevent assigning to them. In your example, you would write

Protect[a, b]; Options[f] = {a -> a0, b -> b0};

then

a = 1;
Set::wrsym: Symbol a is Protected. >>
a
a
Attributes[a]
 {Protected}

and similarly for b.

$\endgroup$
5
$\begingroup$

Instead of protecting option variables that is sacrifice useful names,

I generally use meaningful strings:

Options[f] = {"a" -> a0, "b" -> b0};

f[x_, OptionsPattern[]] := {x, OptionValue["a"]}

Any objections are very welcomed but this worked for me so far.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.