1
$\begingroup$

I'm looking to access variables in different contexts. The contexts are stored in a list labeled contexttable. Each context, of course, is a string. Is there any way, without using NotebookWrite, to access a variable of the same name, say x, in each context?

I am looking for something like

 contexttable = {"Context1`", "Context2`", ..., "ContextN`"};
 Map[Print[# <> x]&, contexttable]

which would print the x variable in each context.

$\endgroup$
1
  • 2
    $\begingroup$ Look up Symbol or ToExpression in the docs. Be aware that if the variable you reference does not exist, you will create a new symbol by using those. $\endgroup$ Mar 29, 2013 at 22:13

2 Answers 2

1
$\begingroup$

As Leonid Shifrin said in his comment, you can use SymbolName and ToExpression to get the values in each context.

{Context1`x, Context2`x} = {"foo", 42}; 
contexttable = {"Context1`", "Context2`", "Context3`"};
ToExpression[# <> SymbolName @ Unevaluated @ x] & /@ contexttable

{"foo", 42, Context3`x}

$\endgroup$
0
$\begingroup$

Also following Leonid's comment, and borrowing from m_goldberg's answer, if you wish to avoid creating new symbols you can use Names to filter before passing to Symbol:

{Context1`x, Context2`x} = {"foo", 42};
contexttable = {"Context1`", "Context2`", "Context3`"};

Symbol /@ Names[# <> "x" & /@ contexttable]
{"foo", 42}

Here Context3`x is never created and only the values for Symbols that exist are returned. This may or may not be desirable. If creation of new Symbols is desired just leave out Names:

Symbol[# <> "x"] & /@ contexttable
{"foo", 42, Context3`x}

Note that in each case the symbol name is given as a string, which greatly simplifies things.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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