Reputation: 26942
As noted elsewhere, you can list all user-defined symbols with this:
Names["Global`*"]
But I'd like to find just my global variables (I'm in the middle of some hairy debugging), not my function definitions. Something like this is close:
Select[Names["Global`*"], Head@Symbol[#]=!=Symbol && Head@Symbol[#]=!=Function&]
But that misses variables whose value is a symbol (perhaps I have x = Pi
).
I could probably beat that thing into submission but maybe there's a cleaner, more direct way?
Upvotes: 13
Views: 5267
Reputation: 24336
One might consider a variable to be a Global`
symbol that does not pass FunctionQ
.
Upvotes: 1
Reputation: 18271
If we consider any symbol with an own-value as a "variable", then this will do the trick:
ClearAll[variableQ]
variableQ[name_String] := {} =!= ToExpression[name, InputForm, OwnValues]
Select[Names["Global`*"], variableQ]
Note that this technique will fail on read-protected symbols and will misidentify some forms of auto-loaded functions.
Edit 1
As @Szabolcs points out, the definition of variableQ
can be simplified if ValueQ
is used:
variableQ[name_String] := ToExpression[name, InputForm, ValueQ]
Edit 2
As @dreeves points out, it might be desirable to filter out apparent variables whose values are functions, e.g. f = (#+1)&
:
variableQ[name_String] :=
MatchQ[
ToExpression[name, InputForm, OwnValues]
, Except[{} | {_ :> (Function|CompiledFunction)[___]}]
]
This definition could be easily extended to check for other function-like forms such as interpolating functions, auto-loaded symbols, etc.
Upvotes: 15