Function Repository Resource:

NeedsDefinitions

Source Notebook

Equivalent to Needs, but does not modify the $ContextPath

Contributed by: Richard Hennigan (Wolfram Research)

ResourceFunction["NeedsDefinitions"]["context`"]

loads an appropriate file if the specified context is not already in $Packages and leaves $ContextPath unchanged.

ResourceFunction["NeedsDefinitions"]["context`","file"]

loads file if the specified context is not already in $Packages.

Details and Options

ResourceFunction["NeedsDefinitions"]["context`"] calls Needs["context`"], which in turn calls Get["context`"]. By convention, the file loaded in this way is the one that contains a package that defines context`.
ResourceFunction["NeedsDefinitions"]["file`"] typically reads in a file named file.m.
Symbols defined in the package loaded by ResourceFunction["NeedsDefinitions"] can be used by their fully qualified names.

Examples

Basic Examples (3) 

Read in the file for the Computer Arithmetic Package if it has not already been read:

In[1]:=
ResourceFunction["NeedsDefinitions"]["ComputerArithmetic`"]

The context path is unchanged:

In[2]:=
$ContextPath
Out[2]=

Symbols defined in the package can be used by their fully qualified names:

In[3]:=
?ComputerArithmetic`Ulp
Out[3]=
In[4]:=
ComputerArithmetic`Ulp[1000.]
Out[4]=

Applications (2) 

Write a function that loads definitions in another package if needed while avoiding naming conflicts:

In[5]:=
MeanCI[data_] := (ResourceFunction["NeedsDefinitions"][
    "HypothesisTesting`"]; Interval[HypothesisTesting`MeanCI[data]]);
In[6]:=
MeanCI[{1, 2, 4, 6, 3}]
Out[6]=

Since HypothesisTesting` is kept off the context path, there is no naming conflict with MeanCI:

In[7]:=
Names["*`MeanCI"]
Out[7]=

Version History

  • 1.0.0 – 06 May 2020

Related Resources

License Information