For any symbol, how can I get the full context-qualified name of the symbol as a string?
This is a variation of Leonid's answer that avoids the dependence on a context like "Test`"
that must be empty:
SetAttributes[fq, {Listable, HoldAll}];
fq[sym_] := Block[{Internal`$ContextMarks = True},ToString[Unevaluated[sym]]]
fq[{fq, Print, Developer`$MaxMachineInteger}]
(* {"Global`fq", "System`Print", "Developer`$MaxMachineInteger"} *)
This works, though it'd be nicer to have a built-in way to do it:
SetAttributes[fullyQualifiedName, {HoldAll, Listable}];
fullyQualifiedName[a_] := Context[a] <> SymbolName[Unevaluated@a]
Some demonstrations:
In[4]:= fullyQualifiedName[a]
Out[4]= "Global`a"
In[5]:= foo = 3
Out[5]= 3
In[6]:= fullyQualifiedName[foo]
Out[6]= "Global`foo"
In[7]:= fullyQualifiedName[Plot]
Out[7]= "System`Plot"
In[9]:= fullyQualifiedName[Developer`$MaxMachineInteger]
Out[9]= "Developer`$MaxMachineInteger"
Here is an alternative:
ClearAll[f];
SetAttributes[f, HoldAll];
f[a_Symbol] :=
Block[{$ContextPath = {"Test`"}, $Context = "Test`"},
ToString[Unevaluated@a]
];
It is based on the way Mathematica treats short and long names depending on the current settings of $Context
and $ContextPath
. The context "Test`"
must not exist for it to be fully bulletproof (it will produce short names for symbols in "Test`"
otherwise), you can use some random string for it. The function produces the same output as yours. You can make it Listable
as well, but for speed, it may be better to add a special rule for a list of symbols, so that the context is changed only once.