Consider the following code:
Begin["mycontext`"];
myvar = 7;
Print[Context[]];
Print[Context[myvar]];
End[];
with the output
mycontext`
mycontext`
Now consider the same code inside a Do-loop:
Do[
Begin["mycontext`"];
myvar = 7;
Print[Context[]];
Print[Context[myvar]];
End[];
, {i,1,2}];
which produces the output
mycontext`
Global`
mycontext`
Global`
What is going on here? Why is myvar considered to be in "Global`"? Even if I force the definition to
mycontext`myvar = 7;
it will still be considered to be global. How do I use contexts inside loops correctly?
The whole point of doing this is the following: I have several similar configuration files (that only contain variables) in "./folder1/config.m" and "./folder2/config.m" etc. which I have to apply some manipulations to. My idea is to loop over all folders, use a local context, Get["./folderX/config.m"], write some new values for the variables, and then Save["./folderX/config.m", "mycontext`"].
Example config.m
currentfolderstuff = 0;
anotherfolderstuff = 0;
What I want to do
Do[
(* some sophisticated stuff with many variable names that will pollute my local context *)
a = i^2 + 7^2 + ...;
b = somefunc[i];
Begin["mycontex`"];
Get["./folder"<>ToString[i]<>"/config.m"];
currentfolderstuff = a;
anotherfolderstuff = b;
Save["./folder"<>ToString[i]<>"/newconfig.m", "mycontext`"];
End[];
, {i,1,2}];
Get
is affected byBegin
becauseGet
needs to parse the contents of a file. Regarding config files: I recommend storing config data as associations instead of code (i.e. several assignment lines). $\endgroup$BeginPackage
, just enclose theGet
inBlock[{$ContextPath = {"mycontext`", "System`"}, $Context = "mycontext`"}, Get[...]]
.BeginPackage
does other things too which you do not want. $\endgroup$