0
$\begingroup$

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.

$\endgroup$
2
  • 1
    $\begingroup$ Begin? $\endgroup$
    – Jason B.
    Commented May 19, 2016 at 9:27
  • $\begingroup$ it looks like there are some good solutions, more in-depth than mine, in that linked post $\endgroup$
    – Jason B.
    Commented May 19, 2016 at 10:59

1 Answer 1

2
$\begingroup$

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[]

$\endgroup$
5
  • $\begingroup$ I worried that this might be the best answer. Thanks anyways $\endgroup$
    – Basti
    Commented May 19, 2016 at 10:16
  • 1
    $\begingroup$ @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 $\endgroup$
    – Jason B.
    Commented May 19, 2016 at 10:56
  • $\begingroup$ That's just slightly more convenient :D $\endgroup$
    – Basti
    Commented May 19, 2016 at 12:11
  • $\begingroup$ @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... $\endgroup$
    – Jason B.
    Commented May 19, 2016 at 18:14
  • $\begingroup$ 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. $\endgroup$
    – Basti
    Commented May 20, 2016 at 5:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.