Skip to main content

packages - Begin["`Private`"] vs Module


So, if you have a package formatted like so:


BeginPackage["MyPackage`"];
Begin["`Private`"];

someFunction:=(
x=3;
y=4;
out=x + y;
)
End[];

Begin["`Private`"];
anotherFunction:=(
x=5;

z=7;
out= x + z;
)
End[];
EndPackage[];

Is x treated locally? Like if you call the function anotherFunction, does Mathematica know the difference between the xs since they both have the context MyPackage`Private or is each instance of Private independent of the other? If so, then why use Module to make variables local rather than the Private context.



Answer



Reading How symbol lookup actually works will teach you that your code produces such definitions:


MyPackage`Private`someFunction:=(

MyPackage`Private`x = 3
; MyPackage`Private`y = 4
; MyPackage`Private`out = MyPackage`Private`x + MyPackage`Private`y
)

MyPackage`Private`x in both functions is the same and there is no mechanism which will prevent those values from interfering. Put e.g Print[x] at the beginning of each definition are run them, you will see that the value of x is known mutually.


So approach with only Begin won't break this code but in general it will cause problems.


With Module the code will look similarly:


MyPackage`Private`someFunction:= Module[
{ MyPackage`Private`x

, MyPackage`Private`y
, MyPackage`Private`out
}
, MyPackage`Private`x=3
; MyPackage`Private`y=4
; MyPackage`Private`out = MyPackage`Private`x+MyPackage`Private`y
]

But once someFunction is called Module will rename x to x$123 (different each time someFunction is called). This makes the value really localized. You can read more in use cases for different scoping constructs


Further reading: Where does a package have to be loaded?



Comments