6
$\begingroup$

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 ?

$\endgroup$
4
  • 1
    $\begingroup$ That'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. $\endgroup$
    – Kuba
    Commented May 28, 2015 at 11:06
  • $\begingroup$ SettingUpWolframLanguagePackages $\endgroup$
    – Kuba
    Commented May 28, 2015 at 11:13
  • $\begingroup$ I used that before and I just notice that I had a syntax error : Begin["Private``"] instead of Begin["``Private``"]. Thank you @Kuba $\endgroup$
    – sekisushai
    Commented May 28, 2015 at 12:27
  • $\begingroup$ Np. p.s. you need double `` to escape ` from inside. $\endgroup$
    – Kuba
    Commented May 28, 2015 at 12:28

1 Answer 1

9
$\begingroup$

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[];
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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