This is documentation for Mathematica 3, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.2)
 Documentation / Mathematica / Add-ons / Standard Packages / Appendix: How Mathematica Packages Are Set Up  /

Loading Packages

Contexts in Mathematica are used to specify packages in a way that is independent of the particular computer system being used. From this point of view, loading a package is simply a way of making a particular context available. The global variable $Packages gives a list of the contexts corresponding to all the packages that have been loaded in your current Mathematica session.


Ways to load packages.

You have already seen how to explicitly read in a package using the command <<context`, or equivalently, Get["context`"]. Often, however, you will want to read in a particular package only if it is needed. The command Needs["context`"] tells Mathematica to read in a package if the context associated with that package is not already in the list $Packages.
Some packages are not designed to be loaded twice and large packages may take a while to load. You should use Needs if you are unsure whether you have loaded a particular package in your current session. Some packages are set up so that when they are loaded, other related packages are automatically loaded at the same time. Packages may have been loaded that you haven't explicitly read in, so it is best to let Mathematica decide which packages need loading.
When you set up a large collection of Mathematica packages, it is a good idea to create an initialization package or "names file" that 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 initialization package. When you have done this, all the other packages will automatically be loaded if and when they are needed. Initialization packages and autoloading packages via the Autoload directory are discussed in detail in the next section.

  • The package context list initially contains only the Global` and System` contexts. Usually new symbols are introduced in the context Global`. Built-in symbols are in the context System`.
  • In[1]:= $Packages

    Out[1]=

  • This specifies that the symbols Div, Grad, and Curl are defined in Calculus`VectorAnalysis`. Now Needs["Calculus`VectorAnalysis`"] will be executed if any of these symbols are used.
  • In[2]:= DeclarePackage["Calculus`VectorAnalysis`",
    {"Div", "Grad", "Curl"}]

    Out[2]=

  • When you first use Grad, Mathematica automatically loads the package Calculus`VectorAnalysis`.
  • In[3]:= Grad[x^2 + y^2, Cartesian[x, y, z]]

    Out[3]=

  • The package's context has been prepended to $Packages.
  • In[4]:= $Packages

    Out[4]=