Skip to main content
4 of 9
added 287 characters in body
jVincent
  • 14.8k
  • 1
  • 44
  • 76

This is a problem relating to how Context changes evaluate. I don't think you can start and stop a context within other evaluations I belive they don't take effect until the expressions are returned to the notebook. Consider the two different pieces of code:

Remove[test`x, x]
(
Begin["test`"];
x = 42;
End[];
{x, test`x}
)

{42,test`x}

And

Remove[test`x, x]
Begin["test`"];
x = 42;
End[];
{x, test`x}

{x,42}

In the first example the compound expressions means the context change doesn't take effect. I belive this is the same problem you are experiencing.

Update

I was speaking simply from my previous experiance and I was slightly wrong on the reasoning, but the effect is quite the same. the reason you cannot scope your variables in the compound expression is because during it's evaluation all symbols will apear before any evaluation of the context changing, therefore you will actually change the context, but all symbols will already have been scoped to the original context. In order to get around this, you have to somehow evaluate your expression without exposing any symbols, this can be done by converting it to box form, changing context and converting it back to an expressions, here's a short example. Note that I change the context path to exclude System``` in order to have MakeBoxes retain any mention to this context, this way you won't end up with x=Sin[0]``` being evaluated to test``x=test``Sin[0].

SetAttributes[ContextScope, HoldAll]
ContextScope[context_, expression_, exclude_: {"System`"}] :=
Module[{held},
Block[{$ContextPath = Complement[$ContextPath, {"System`"}]}, held = MakeBoxes[expression]];
Block[{$Context = context, $ContextPath = {context}}, 
 ToExpression[held, StandardForm]]
]

ContextScope["test`", x = 42]
{x, test`x}

{x,42}

This will however still put Global``x in scope, it simply does not assing a value to it. So any new call to x=somethign will assign a value to Global``x and not to test``x as would normally be expected if you had done a line by line evaluation of the context switching.

jVincent
  • 14.8k
  • 1
  • 44
  • 76