When writing a Mathematica package Foo, with functions f1, f2 and f3, one can use the template:
BeginPackage["Foo`"];
f1::usage = "f1[] ....";
f2::usage = "f2[] ....";
Begin["`Private`"];
f1[]:= code for f1
f2[]:= code for f2
f3[]:= code for f3 (not visible as only in the private context)
End[];
EndPackage[];
What I do not like is when your package is growing, there can be a long "distance" (not fitting in your text editor) between "f1::usage" and the actual f1 code. This is error prone concerning coherence between doc and code. So I would like to group common stuff together.
My question is:
Is it possible and is it a good practice (without side effect) to group things like below?
BeginPackage["Foo`"];
Begin["`Private`"];
Foo`f1::usage = "f1[] ....";
Foo`f1[]:= code for f1
...
Foo`f2::usage = "f2[] ....";
Foo`f2[]:= code for f2
...
f3[]:= code for f3 (private as before)
End[]
EndPackage[];
Answer
The key point is not to set the usage message between BeginPackage
and Begin["`Private`"]
, but just to mention the symbol.
A better way to do this would be:
BeginPackage["Foo`"];
f1
f2
Begin["`Private`"];
f1::usage = "f1[] ....";
f1[]:= code for f1
f2::usage = "f2[] ....";
f2[]:= code for f2
f3[]:= code for f3 (not visible as only in the private context)
End[];
EndPackage[];
Whatever you mention there will be a public symbol (f1
, f2
). What you don't mention will not be public (f3
). That's because after the BeginPackage
, $Context
will be Foo`
, meaning that new symbols are created there. $Context
controls where new symbols are created. After the Begin["`Private`"]
, $Context
is changed, but Foo`
is still in $ContextPath
. $ContextPath
controls where Mathematica should look for symbol names. It only creates a new symbol if it didn't find the name in $ContextPath
.
You could use the explicit context for every definition, but personally I don't like this because it keeps repeating the name of the context, thus making it difficult to change in the future. It is also good to point out that you'd only need to use an explicit context when mentioning the symbol for the first time. I.e. this would be sufficient (though potentially confusing):
Foo`f1::usage = "f1[] ....";
f1[]:= code for f1
It is good practice to use different naming conventions for public and non-public symbols. Public ones are preferably capitalized. This will also help in catching errors such as not making a symbol public.
Comments
Post a Comment