0
$\begingroup$

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.

$\endgroup$
2
  • 5
    $\begingroup$ Take a look at SymbolName $\endgroup$ Commented Oct 25, 2017 at 11:47
  • $\begingroup$ related: 32223, 15687, 119922, 17916 $\endgroup$ Commented Oct 25, 2017 at 11:51

1 Answer 1

7
$\begingroup$

You can use SymbolName.

foo`bar (* foo`bar *) ToString[foo`bar] (* "foo`bar" *) SymbolName[foo`bar] (* "bar" *) 

Warning:

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.

$\endgroup$
2
  • $\begingroup$ Sorry I didn't understand the warning. What did you mean by different contexts ? Did you mean different scopes or different namespaces ? $\endgroup$ Commented Oct 25, 2017 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$ Commented Oct 25, 2017 at 12:57

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.