Tips to cope with scoping rules of top level `for` loops etc

I agree wholeheartedly on this. I love having the global very explicit when you really want global variables. This is one of the reasons I hate the current solution: you are annotating something as a global that you don’t really want as a global outside of the current script.

The core of this issue is that in an interactive/script style programming, global variables are the wrong mental model for variables inside of a loop at the top level. Instead, the mental model of matlab and the scripting languages is that the variables are local to the script or the (or jupyter notebook) itself. Another mental model from C would be that there is a big void main() function around the script, and the variables are local to that main and not truly global unless you annotate them as such. This is the reason that people get confused with the current v1.0 behavior, and expect top level code to be equivalent to wrapping the whole script in a function and call it. They don’t think of the variables as being globals.

I think the best mapping of the mental model to julia’s scope would be that when they write a script, we should think of the whole thing being wrapped in a big let block.

Of course, the main() model breaks down in implementation. Actually having variables local to a script (or jupyter notebook) or the REPL doesn’t work in a dynamic and interactive language, which is why it is necessary to make them be global as an implementation detail for practical reasons. I don’t think there is a way to reconcile this without some special cases.

If you have been using “real” programming languages for a long time, and haven’t programmed in a scripting style recently, then this distinction may seem artificial, but it is extremely intuitive. Similarly, if you are largely working on writing packages, this distinction is irrelevant since the only globals you would have are intentional globals. The proof that this is intuitive is that SoftGlobalScope (which effectively emulates what I am talking about) and the old Julia v0.6 behavior was never confusing to introductory users. Leave global for when people intentionally want a global variable.

1 Like