Automatic Loading of Packages

Other tutorials have discussed explicit loading of Wolfram Language packages using <<package and (RefLink[Needs, paclet:ref/Needs])[package]. Sometimes, however, you may want to set the Wolfram Language up so that it automatically loads a particular package when the package is needed.

You can use (RefLink[DeclarePackage, paclet:ref/DeclarePackage]) to give the names of symbols which are defined in a particular package. Then, when one of these symbols is actually used, the Wolfram Language will automatically load the package where the symbol is defined.

Arranging for automatic loading of packages.

This specifies that the symbols (PackageLink[VariationalD, paclet:VariationalMethods/ref/VariationalD, VariationalMethods Package Symbol]), (PackageLink[EulerEquations, paclet:VariationalMethods/ref/EulerEquations, VariationalMethods Package Symbol]), and (PackageLink[FirstIntegral, paclet:VariationalMethods/ref/FirstIntegral, VariationalMethods Package Symbol]) are defined in (RefLinkPlain[VariationalMethods`, paclet:VariationalMethods/guide/VariationalMethodsPackage]):

DeclarePackage["VariationalMethods`",{"VariationalD","EulerEquations","FirstIntegral"}]

When you first use (PackageLink[VariationalD, paclet:VariationalMethods/ref/VariationalD, VariationalMethods Package Symbol]), the Wolfram Language automatically loads the package that defines it:

VariationalD[Sqrt[1+y'[x]^2],y[x],x]

When you set up a large collection of Wolfram Language packages, it is often a good idea to create an additional “names file” which contains a sequence of (RefLink[DeclarePackage, paclet:ref/DeclarePackage]) commands, specifying packages to load when particular names are used. Within a particular Wolfram System session, you then need to load explicitly only the names file. When you have done this, all the other packages will automatically be loaded if and when they are needed.

(RefLink[DeclarePackage, paclet:ref/DeclarePackage]) works by immediately creating symbols with the names you specify, but giving each of these symbols the special attribute (RefLink[Stub, paclet:ref/Stub]). Whenever the Wolfram Language finds a symbol with the (RefLink[Stub, paclet:ref/Stub]) attribute, it automatically loads the package corresponding to the context of the symbol, in an attempt to find the definition of the symbol.