up

How to make a package in Mathematica

Nasser M. Abbasi, 7/16/2010

This note describes making a simple package in Mathematica. An example package that contains one function is made showing how to save it and load it into Mathematica and to update it again by adding a second function to it.

Each time a new function is added to the package, the package has to be reloaded.

This note is not meant by any means to be comprehensive, but only to give someone who is new at using Mathematica the minimal set of commands to make a basic package.

More details about packages are found in Mathematica help pages.

1.
Open a new notebook, and write in it the following code in one cell.
  BeginPackage["foo"]
  Unprotect @@ Names["foo*"];
  ClearAll @@ Names["foo*"];
  
  f::usage = "f[x]"
  Begin["Private"]
  
  f[x_] := Module[{}, x^2];
  
  End[]
  Protect @@ Names["foo*"];
  EndPackage[]
2.
Select the cell and change the cell to become an initialization cell as follows:
  Cell->Cell Properties->Initialization Cell.
3.
Now save the notebook. Select Save As. Assuming it is saved as
       C:\mydata\foo.nb

A pop-up menu will now ask you about an AUTO SAVE choice, this will happen just before the save is completed, there will be two choices, select the LEFT option by clicking on it.

PIC

Now that package is saved. You can close the file foo.nb

4.
To use the function f[x] defined in the package, load the package as follows (this is one easy way to load the package, there are other ways).
  Get["c:\\mydata\\foo.m"]

Notice the name used above, it is foo.m and not foo.nb, and notice that the path has two slashes in it.

Now, the package is loaded and you can call the function defined inside the package as follows

f[2]

The function can also be called by explicitly pre-appending the package name to the function as follows (this is not necessary, but it can be useful)

  foof[2]
5.
To add a second function, say g[x] to the package, open foo.nb again, and change it to look as follows:
  BeginPackage["foo"]
  Unprotect @@ Names["foo*"];
  ClearAll @@ Names["foo*"];
  
  f::usage = "f[x]"
  g::usage = "g[x]"
  Begin["Private"]
  
  f[x_] := Module[{}, x^2];
  g[x_] := Module[{}, x^4];
  
  End[]
  Protect @@ Names["foo*"];
  EndPackage[]

Now save the file foo.nb. Notice that now Mathematica will not ask again about the Auto Save option. This question is only asked the first time.

6.
Close foo.nb. To use the new function added to the package, the package needs to be reloaded again
Get["c:\\mydata\\foo.m"]

7.
To see which functions in your package type
?foo‘*

That is all. To add more functions, repeat the above 3 steps.

I'd like to thank Bill Rowe and Istvan Zachar on the Math newsgroup for helpfull suggestions while working on this note.