Function Repository Resource:

SymbolDependencies

Source Notebook

Get a list of symbols that an expression depends on

Contributed by: Richard Hennigan (Wolfram Research)

ResourceFunction["SymbolDependencies"][sym]

finds symbols that appear in the definition of sym.

ResourceFunction["SymbolDependencies"][sym,h]

wraps the head h around each symbol before returning.

ResourceFunction["SymbolDependencies"][sym,h,n]

recursively finds symbols using up to n steps.

Details and Options

ResourceFunction["SymbolDependencies"][sym] is equivalent to ResourceFunction["SymbolDependencies"][sym,Identity].
In ResourceFunction["SymbolDependencies"][sym,h,n], n can be a positive integer or All.
ResourceFunction["SymbolDependencies"] has the following options:
"IgnoringUndefined"Falsewhether to return undefined symbols
"IgnoreModuleSymbols"Truewhether to return symbols that were created by Module
"Self"Falsedecide if a symbol depends on itself
"ExcludedContexts"Automaticwhich contexts to ignore when looking for symbols

Examples

Basic Examples (4) 

Get the dependencies of a symbol:

In[1]:=
f[x_] := g[x];
g[x_] := h[x + 1];
h[x_] := 2 x;
ResourceFunction["SymbolDependencies"][f]
Out[4]=

Apply a wrapper to each symbol:

In[5]:=
x = 1;
ResourceFunction["SymbolDependencies"][f, Hold]
Out[6]=

Specify a level:

In[7]:=
ResourceFunction["SymbolDependencies"][f, Hold, 2]
Out[7]=

Get full dependencies:

In[8]:=
a := b; b := c; c := d; d := e;
ResourceFunction["SymbolDependencies"][a, Hold, All]
Out[9]=

Scope (1) 

Any expression can be used in the first argument:

In[10]:=
ResourceFunction["SymbolDependencies"][f[y, z]]
Out[10]=

Options (6) 

IgnoringUndefined (1) 

Ignore undefined symbols:

In[11]:=
ResourceFunction["SymbolDependencies"][f[y, z], "IgnoringUndefined" -> True]
Out[11]=

IgnoreModuleSymbols (2) 

By default, local symbols left over from Module evaluations are ignored:

In[12]:=
expr = Module[{f}, f[x_] := x + 1; f]
Out[12]=
In[13]:=
ResourceFunction["SymbolDependencies"][expr]
Out[13]=

Include Module symbols:

In[14]:=
ResourceFunction["SymbolDependencies"][expr, "IgnoreModuleSymbols" -> False]
Out[14]=

Self (2) 

By default, the given symbol will not be included in the output:

In[15]:=
ClearAll[f, x];
f[0] = 1;
f[x_] := x*f[x - 1];
ResourceFunction["SymbolDependencies"][f]
Out[18]=

Include the symbol:

In[19]:=
ResourceFunction["SymbolDependencies"][f, "Self" -> True]
Out[19]=

ExcludedContexts (1) 

Exclude symbols from specific contexts:

In[20]:=
ResourceFunction["SymbolDependencies"][MyContext`g[f[n]], "ExcludedContexts" -> {"System`", "Global`"}]
Out[20]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.1 – 09 January 2023
  • 1.0.0 – 11 October 2018

Related Resources

License Information