2
$\begingroup$

How do I get the list of all OwnValues of symbols in the Global` context?

All my attempts have failed because OwnValues insists taking only Symbol, and Names[] only returns a list of String:

ClearAll["Global`*"]
a = 3;
OwnValues[Evaluate[Symbol[#]]] & /@ Names["Global`*"]

OwnValues::sym : Argument 3 at position 1 expected to be a symbol

{OwnValues[3]}

Converting the String to Symbol causes the Symbol to evaluate before it enters OwnValues.

$\endgroup$
  • 2
    $\begingroup$ Somebody will find the duplicate, but in the mean time, you can use: Cases[Names["Global`*"], x_ /; ToExpression[x, InputForm, OwnValues]=!={}] $\endgroup$ – Carl Woll Jul 15 '17 at 18:28
  • 2
    $\begingroup$ Also, Language`ExtendedDefinition is a useful function that accepts strings and returns a list of *Values plus a few other pieces of information. $\endgroup$ – Carl Woll Jul 15 '17 at 18:32
2
$\begingroup$

Using the same code structure, for example, you can use the fact that MakeExpression returns HoldComplete:

ClearAll["Global`*"]
a = 3;
ReleaseHold@Hold[OwnValues][MakeExpression[#]] & /@ Names["Global`*"]

{{HoldPattern[a] :> 3}}

edit

Then using b3m2a1's suggestion,

Join@@ToExpression[Names["Global`*"], StandardForm, OwnValues]

returns the desired list.

$\endgroup$
  • $\begingroup$ Use the third argument to ToExpression to make this more concise. i.e. ToExpression[Names["Global`*"], StandardForm, OwnValues] $\endgroup$ – b3m2a1 Jul 16 '17 at 0:28
  • $\begingroup$ @b3m2a1 ...and using Join to put it all together: Join@@ToExpression[Names["Global`*"], StandardForm, OwnValues] $\endgroup$ – QuantumDot Jul 16 '17 at 3:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.