Naming conflicts with Dummy variables in several packages conflicts

6

1

I'm using several packages in a notebook. In each packages there is functions defined with dummy variables. When I load the several packages in my session, i've got a warning message:

BeginPackage["square`"];
square[x_] := x^2;
EndPackage[]
BeginPackage["cube`"];
cube[x_] := x^3;
EndPackage[]

x::shdw: Symbol x appears in multiple contexts {cube,square}; definitions in context cube` may shadow or be shadowed by other definitions. >>

I don't really understand since the variable x should be dummy ?

Pierre

Posted 2015-05-28T10:39:32.180

Reputation: 325

1That's why you should write definitions in additional Begin["`Private`"] ... End[]; statements. Symbols created there are not exported outside since End does not modify $ContextPath. – Kuba – 2015-05-28T11:06:40.527

SettingUpWolframLanguagePackages – Kuba – 2015-05-28T11:13:54.690

I used that before and I just notice that I had a syntax error : Begin["Private``"] instead of Begin["``Private``"]. Thank you @Kuba – Pierre – 2015-05-28T12:27:09.643

Np. p.s. you need double `` to escape ` from inside. – Kuba – 2015-05-28T12:28:35.700

Answers

9

There are two things you need to know:

(1.) Mathematica knows about symbols, even if you only mention them: This means that in this simple example

1 /. myVar_Integer :> 0

where myVar is only a placeholder (a named pattern) or like you call it a dummy, Mathematica still sees this symbol and adds it to its symbol table

Names["Global`*"]
(* {"myVar"} *)

(2.) Since a context created with BeginPackage is added to the $ContextPath when you call EndPackage, all symbols created there are accessible after loading the package. Therefore, the general rule when creating packages is to protect most internal code (like your definition) within another private context introduced with Begin.

Therefore, what you should do is to use the usual boiler-plate code until you understood all implications:

BeginPackage["cube`"];
cube::usage = "cube";
Begin["`Private`"];
cube[x_] := x^2;
End[];
EndPackage[];

halirutan

Posted 2015-05-28T10:39:32.180

Reputation: 109 574