Strange loop behavior when assigning variable within loop


I’m confused about the following behavior:

julia> a = 2019

julia> for i in 1:2
           a = 57
ERROR: UndefVarError: a not defined
 [1] top-level scope at ./REPL[2]:3 [inlined]
 [2] top-level scope at ./none:0

I would have thought that this would have printed:


Can someone explain where my thinking is going wrong?


The relevant section in the manual is here. To be specific:

In a local scope, all variables are inherited from its parent global scope block unless:

  • an assignment would result in a modified global variable, or

In other words, since a = 57 is an assignment that would result in a modified global variable, a is not inherited from the global REPL scope, so trying to access it with println(a) results in an a not defined error.

If you want the output you suggest, you can use global a = 57 to change the global variable.


Hmm, strange, on Juliabox using 1.0.3 this works the way I would expect though:

It’s only on my machine it has this error.

I ran it with --startup-file=no and even renamed the startup file to be sure it was a vanilla REPL.

Any suggestions? Why would this behavior differ between different installs of the same version of Julia?

1 Like

Following up: looks like this also works in my local Jupyter install. Here’s a screenshot from an IJulia console session:

Seems like IJulia and the Julia REPL treat these differently for some reason?

1 Like

This is the “soft global scope” problem

I believe the behavior in jupyter is different to the REPL because jupyter uses as a workaround for the somewhat unintuitive behavior of the new scoping rules in julia-1.0. (The rules changed only for code executed at “top level” - ie outside a function.)

There’s been a lot of discussion on this forum about this particular issue which you can find if you search for things like “soft global scope”.


I guess shoutout to this comment, as that is exactly what happened in this case: