# Module, block or whatever to scope variables without explicitly listing them? [duplicate]

In larger notebooks I have often trouble with conflicting variable names. To combat this there are Modules and blocks. But with those you always have to list the variables you are using. I don't understand the need for this. Is there an alternative where you just open a scope of some kind, and everything is local to that scope? That's a feature of pretty much every other programming language has and I'm desperately missing.

• May 19 '16 at 9:27
• it looks like there are some good solutions, more in-depth than mine, in that linked post May 19 '16 at 10:59

Begin may be what you need here, as it allows you to define variables inside a given Context:

a = 3;
Begin["MyContext"];
{a, b, c} = {1, 2, 3};
Print@{a, b, c};
End[];
Print@{a, b, c}
Print@{MyContexta, MyContextb, MyContextc}


{1,2,3}

{1,b,c}

{MyContexta,2,3}

There are a couple of important caveats: If you have already given a variable a name in the Global context, then you cannot define a variable in the new context with that exact same name. Also, when leaving the new context, the defined variables are not cleared, for that you need to do ClearAll["MyContext*"] after you End[]

• I worried that this might be the best answer. Thanks anyways May 19 '16 at 10:16
• @Basti Another option would be to use Module[{x},......] and then define every variable you need inside as a downvalue of x, like x[1], x[2]`, etc May 19 '16 at 10:56
• That's just slightly more convenient :D May 19 '16 at 12:11
• @Basti The way I normally make a Module or Block is to just write all the code as I want it, then all the unscoped variables are still blue. I just add them into the brackets for the scope until there is no blue left. It doesn't take that long to do... May 19 '16 at 18:14
• Yeah I get that. However it's hard to accept that things like that are so incredibly complicated. The power of Mathematica is in no relation to its usability. May 20 '16 at 5:39