When to use Get vs Needs

Needs versus Get

<<name reads in a file, evaluating each expression in it, and returning the last one.

(<< is shorthand for Get.)

Needs["context`"] loads an appropriate file if the specified context is not already in $Packages.

Needs is normally appropriate for making sure that a package has been loaded, but when you need to force the package to reload you want Get. One simple example of the difference is if you have loaded the Notation package but closed the Palette. Calling Needs["Notation`"] will not reload the package, and will not cause the Palette to be re-displayed, whereas Get["Notation`"] will.


Get can be used for loading several different formats containing data or definitions, in addition to formal packages. See this answer for an overview of such methods.


A related function that deserves mentioning is DeclarePackage. While Get does a hard load and Needs does a soft one, DeclarePackage does a delayed load. That is, it only loads the package when a certain Symbol (from a list of one or more) is first used. For example if you might want to use functions from the Calendar package you do not need to load it into memory, but rather may use:

DeclarePackage["Calendar`", {"DayOfWeek", "DaysPlus", "DaysBetween"}]

Now if any of those three functions are used the Calendar package will be transparently loaded and the function will work. Be aware that if other function names from the package are used before one of these three you may create a shadowing problem. You could add all package Symbols to the DeclarePackage statement, or you could just be aware of the problem and act accordingly.


The main difference has been mentioned by Mr.Wizard, and another common situation where you want Get instead of Needs is during development, when you have changed something in a package file and want to reload with these changes applied (which will of course need some care that this reload is working correctly).

But there is another big difference: Needs insists on a correct package format and will complain when the .m file doesn't correctly create a context which matches the file name and path. Get will instead load every file with correct Mathematica InputForm syntax. That means that you can e.g. use Put and Get to save and load arbitrary mathematica expressions to file, which would not be possible with Needs.