Load a mathematica package from within a package

后端 未结 1 1763
迷失自我
迷失自我 2021-01-31 11:56

I have more or less the following setting. In ~/path/to/my/packages I have two packages package1.m and package2.m. Each package\'s outline

相关标签:
1条回答
  • 2021-01-31 12:42

    There are two generally recommended ways to load a package. One is so-called public import, and in your setting it will be done as

    BeginPackage["package2`",{"package1`"}]
    
    (* Usage messages etc *) 
    
    Begin["`Private`"]
    
    (* code here *)
    
    End[]
    EndPackage[]
    

    Here, you indicate the context name of the package you want to load, in the list which is a second optional argument to BeginPackage. This way of importing is called public because the loaded package will remain on the $ContextPath after your main package is loaded, and will thus be publicly available.

    The second method is called private import, and is schematically done as

    BeginPackage["package2`"]
    
    (* Usage messages etc *) 
    
    Begin["`Private`"]
    Needs["package1`"]
    
    (* code here *)
    
    End[]
    EndPackage[]
    

    In this method, your loaded second package will only be available to the package that loads it (with Needs), thus private import.

    Which way you need will depend on the situation. I try to make all my imports private unless I have to make them public. For debugging, however, it may be handy to first make a public import, since then you can play with the second package directly at the top-level.

    As for the safety, you can load a package by any number of packages, and this will be safe. When you load several packages into the same context simultaneously, this will be safe as long as those packages don't have public symbols with the same short name. Otherwise, you will run into what is called a shadowing problem, but it is best to make the effort needed to avoid that (it is always possible).

    0 讨论(0)
提交回复
热议问题