I am using ToString to convert symbols to a string. So my entire code is written assuming ToString[a] will return "a". Now I am converting my notebook to Mathematica package. Now ToString[a] returns "Packagename`Private`a". This breaks my assumptions and so my code breaks;

Is there anyway to tweak like ToStringSafe[a] that returns a e.g. the local name of that symbol. Not the global one.

  • 5
    $\begingroup$ Take a look at SymbolName $\endgroup$
    – Kuba
    Oct 25 '17 at 11:47
  • $\begingroup$ related: 32223, 15687, 119922, 17916 $\endgroup$
    – Kuba
    Oct 25 '17 at 11:51

You can use SymbolName.

(* foo`bar *)

(* "foo`bar" *)

(* "bar" *)


Converting between symbols and strings requires great care, especially when different contexts are involved. Make sure you really need to do this and that you really do not want the fully qualified name. Robust code will not normally convert between strings and symbols.

  • $\begingroup$ Sorry I didn't understand the warning. What did you mean by different contexts ? Did you mean different scopes or different namespaces ? $\endgroup$
    – Neel Basu
    Oct 25 '17 at 12:31
  • 1
    $\begingroup$ @NeelBasu There is no such thing as "local name" or "global name". When you used these words I started to wonder if you have a good understanding of contexts and name resolution. Contexts are kind of like namespaces but not exactly. $\endgroup$
    – Szabolcs
    Oct 25 '17 at 12:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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