When working in a context, I would like all variable assignments to happen on symbols in the new context.
This doesn't normally happen. For example,
Quit[]
x=3
Begin@"mycontext`"
, then
x=4
?? x
produces a value of 4 for Global`x, rather than 3 for Global`x and 4 for mycontext`x as I would prefer in this case. This is because the Global meaning of x is used throughout (because the symbol x has appeared earlier in the Global context).
Is there any code I can add between these two blocks to make this happen? When x is referenced outside of an assignment, I would like x to be interpreted as normal.
I could indeed assign via mycontext`x=4, but what I actually want to do is to insert some context-starting/context-ending commands before/after a block of existing code, such that all variables inside the code will be treated as local, whilst avoiding the downsides of Block or Module. Namely, the downsides are that
- I would have to record each variable name in the first argument of Block/Module,
- I would no longer be able to evaluate the code line-by-line in the notebook.
Is this possible, and if so would there be any ugly side-effects?
$ContextPath
,$Context
,Begin
andBeginPackage
. Your problem is that althoughBegin
changes the$Context
, it does not change the current$ContextPath
which is why the globalx
is found first if it is already defined. $\endgroup$