1
$\begingroup$

The purpose of DeclarePackage is to load a package only when one of the package variables is needed. This works well when the variable is needed in a notebook but causes shadowing errors when the variable is needed in another package.

Is it possible to use variables declared by DeclarePackage also in other packages without shadowing errors?

Example: Let's assume we have toy packages "a`", "a`a1`" and "ab`" in the Applications directory of the user base directory:

Applications/a/Kernel/init.m

BeginPackage["a`"];
EndPackage[];
(* Use DeclarePackage here instead of Needs or Get in order to load package a`a1` only when variable var1 is needed *)
DeclarePackage["a`a1`", {"var1"}];

Applications/a/a1.m

BeginPackage["a`a1`"];
var1::usage = "var1[]; (* -> toy example printing \"this calls a`a1`var1[]\"" *)
var1[] := "this calls a`a1`var1[]";
EndPackage[];

Applications/ab/ab.m

BeginPackage["ab`",{"a`"}];
(* Expected here is to use variable a`a1`var1 -> print context a`a1`*)
Print[Context[var1]];
EndPackage[];

Let's test it in a notebook:

(* Using inside the notebook var1 from package a`a1` does what it should do *)
Needs["a`"];
var1[] (* -> this calls a`a1`var1[] *)
Context[var1] (* -> a`a1`*)

(* After loading package ab` variable a`a1`var1 is shadowed by an unwanted variable ab`var1 *)
Needs["ab`"] 

var1::shdw: Symbol var1 appears in multiple contexts {ab`,a`a1`}; definitions in context ab` may shadow or be shadowed by other definitions.

Is it possible to declare variables by DeclarePackage without shadowing errors (and not to use Needs or Get inside Applications/a/Kernel/init.m?)

$\endgroup$

0

Your Answer

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

Browse other questions tagged or ask your own question.