Automatic Loading of Packages

Other tutorials have discussed explicit loading of Mathematica packages using <<package and Needs[package]. Sometimes, however, you may want to set Mathematica up so that it automatically loads a particular package when the package is needed.

You can use DeclarePackage to give the names of symbols which are defined in a particular package. Then, when one of these symbols is actually used, Mathematica will automatically load the package where the symbol is defined.

DeclarePackage["context`",{"name1","name2",...}]
declare that a package should automatically be loaded if a symbol with any of the names is used

Arranging for automatic loading of packages.

This specifies that the symbols Div, Grad, and Curl are defined in VectorAnalysis`.
In[1]:=
Click for copyable input
Out[1]=
When you first use Grad, Mathematica automatically loads the package that defines it.
In[2]:=
Click for copyable input
Out[2]=

When you set up a large collection of Mathematica packages, it is often a good idea to create an additional "names file" which contains a sequence of DeclarePackage commands, specifying packages to load when particular names are used. Within a particular Mathematica 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.

DeclarePackage works by immediately creating symbols with the names you specify, but giving each of these symbols the special attribute Stub. Whenever Mathematica finds a symbol with the Stub attribute, it automatically loads the package corresponding to the context of the symbol, in an attempt to find the definition of the symbol.

New to Mathematica? Find your learning path »
Have a question? Ask support »