0

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.

Basti
  • 123
  • 4

1 Answers1

2

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@{MyContext`a, MyContext`b, MyContext`c}

{1,2,3}

{1,b,c}

{MyContext`a,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[]

Jason B.
  • 68,381
  • 3
  • 139
  • 286
  • I worried that this might be the best answer. Thanks anyways – Basti May 19 '16 at 10:16
  • 1
    @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 – Jason B. May 19 '16 at 10:56
  • That's just slightly more convenient :D – Basti 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... – Jason B. 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. – Basti May 20 '16 at 05:39