When should I use <<
vs Needs
? I just always use Needs
as <<
seems less safe. I tried to find the answer in the documentation, but all it really seems to say is that Needs
uses Get
. My understanding is that Needs
will only do the import once, whereas Get
will happily do it again. So is this just a style issue? Or are there reasons to use one or the other?
Answer
Needs
versus Get
<
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.
Comments
Post a Comment