3
$\begingroup$

According to https://reference.wolfram.com/language/workflow/HandleShadowingOfSymbolNames.html when a symbol appears in multiple contexts the one loaded (last?) gets precedence in that that context gets used when no context is explicitly stated. That is if we definea=1, then load a package p1 where say a=2 is defined from that moment a will refer to p1`a taking the value 2.

Is it possible to reverse this behavior? I would like to be able to load a package but be sure that the main code (in the Global context) always takes precedence and still works. I'm happy referring to the symbols in the loaded package by explicitly stating the context, i.e.p1`a.

$\endgroup$

1 Answer 1

3
$\begingroup$

If you are happy referring to the symbols in the loaded package by their full name, then just avoid ever putting that package on the context path.

Instead of using one of these:

Needs["p1`"]
(*or*)
Get["path/to/package.m"]

use

Needs["p1`" -> None]
(*or*)
Block[{$ContextPath},Get["path/to/package.m"]]

and $ContextPath will remain unchanged. You will still see the shadowing messages unless you quiet them, but there will be no ambiguity with respect to the imported symbols.

$\endgroup$
2
  • $\begingroup$ I was loading the package from a .m file using Get. How do I load a package from a file given its path using Needs? $\endgroup$
    – Kvothe
    Mar 8, 2023 at 14:52
  • $\begingroup$ @Kvothe - see the edit $\endgroup$
    – Jason B.
    Mar 8, 2023 at 16:31

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.