2
$\begingroup$

I have a package file MyPackage.wl it has the following commands:

BeginPackage["Me`MyPackage`",{"ExternalContext1`","ExternalContext2`"}] ... Needs["Me`MyPackage`Internal`"]; ... EndPackage[]; 

Now within Internal.wl it has the following commands:

BeginPackage["Me`MyPackage`Internal`",{"Me`MyPackage`"}]; ... EndPackage[]; 

Now I can access the "Me`MyPackage`Internal`", "ExternalContext1`" and "ExternalContext2`" symbols inside MyPackage.wl but within Internal.wl I can only access "Me`MyPackage`" symbols but not "ExternalContext1`" and "ExternalContext2`".

So why are the contexts "ExternalContext1`" and "ExternalContext2`" not being added to the $ContextPath inside Internal.wl. I can always start Internal.wl by:

BeginPackage["Me`MyPackage`Internal`",{"ExternalContext1`","ExternalContext2`","Me`MyPackage`"}]; 

and it would work but as I add more and more ExternalContexts and there are more and more subcontexts, I don't want to keep updating this list inside every single subpackage. What is the better way of doing this?

$\endgroup$
3
  • 1
    $\begingroup$ closely related: Second argument of BeginPackage with nested package loading $\endgroup$ Commented Feb 7, 2024 at 9:14
  • $\begingroup$ @Kuba Do you know about the "HiddenImport" and "PrimaryContext" properties in the newer Paclet System's PacletObject[...]. Can you explain what they are and how they work if you know? $\endgroup$ Commented Feb 8, 2024 at 1:58
  • $\begingroup$ I only found this: What are Package` context symbols for? Never used it though. $\endgroup$ Commented Feb 8, 2024 at 7:23

1 Answer 1

2
$\begingroup$

BeginPackage["pak1`",{"pak2"}] loads pak1 and pak2, but no package that pak2 needs. You can see this by e.g.:

BeginPackage["external`"] $ContextPath EndPackage[] BeginPackage["context1`", {"external`"}] $ContextPath EndPackage[] 

And then:

BeginPackage["internal`", {"context1`"}] $ContextPath EndPackage[] internal` {"internal`", "context1`", "System`"} 

"external"`is not loaded.

To load also packages that a needed package needs, you may define a variable "cPath" that contains the loaded packages like:

BeginPackage["context1`", {"external`"}]; cPath = $ContextPath; EndPackage[]; BeginPackage["internal`", {"context1`"}] Needs /@ context1`cPath; $ContextPath EndPackage[] 

This returns:

context1` {"external`", "internal`", "context1`", "System`"} 

Now "external`" is also loaded.

$\endgroup$
1
  • $\begingroup$ Thank you, I am keeping a variable to keep track of contexts as you suggested. But I am not accepting the answer in case their is a more builtin paclet way of doing this. $\endgroup$ Commented Feb 10, 2024 at 19:52

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.