# 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 MyPackagePrivate 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.

## 1 Answer

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

MyPackagePrivatesomeFunction:=(
MyPackagePrivatex = 3
; MyPackagePrivatey = 4
; MyPackagePrivateout = MyPackagePrivatex + MyPackagePrivatey
)


MyPackagePrivatex 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:

MyPackagePrivatesomeFunction:= Module[
{ MyPackagePrivatex
, MyPackagePrivatey
, MyPackagePrivateout
}
, MyPackagePrivatex=3
; MyPackagePrivatey=4
; MyPackagePrivateout = MyPackagePrivatex+MyPackagePrivatey
]


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? • Is there any reason I cant use Begin["someFunction"] and Begin["anotherFunction"] instead of Begin["Private"] to truly localize the variables inside the functions? – Joe Blow Jun 16 '17 at 6:22 • @JoeBlow Private is only a name, there is nothing special about it. So there is no difference if you use it or your names. Sure it will shield x-es from one and another in those functions in this case, but only if there isn't x already on$ContextPath, e.g. in MyPackage . Then new symbols won't be created. ... – Kuba Jun 16 '17 at 6:27
• @JoeBlow ... Do you want to care about that each time? When package grows and uses other packages internally, a possibility of not uniqueness grows. It does not mean it will break your code, depends what it is about, like here, it does not matter so much. But using this coding style will lead you problems hard to debug. – Kuba Jun 16 '17 at 6:27
• @JoeBlow Module` is the way to go as it shields what it sees, no matter which context is specific symbol in. – Kuba Jun 16 '17 at 6:29
• Thanks for the help. Looks like I have some editing to do. – Joe Blow Jun 16 '17 at 6:36