What I really dislike about Julia? It’s scope.

There are things that just niggle at you all the time. Most of us haven’t had to worry about the likes of scope that closely in decades. You create a global variable, it’s global. You create a variable inside a subprogram, it’s local to that subroutine. Simple right? The problem comes then with dynamically typed languages where variables don’t need to be declared before they are used. They are “declared” at the time of use. So a variable used within a loop for the first time, should be accessible after the loop is finished. I mean that’s how it works in Python. But that’s not how it works in Julia. Consider a piece of Julia code like this:

for i in 1:10
   x = i + i
end
println(x)

Now the println() will fail because the scope of x is inside the for loop, and result in a “x not defined” message. If we try to make x “global” by setting it to zero before the loop (and changing the expression to sum the values of i):

x = 0
for i in 1:10
   x = x + i
end
println(x)

It fails again, leading to a message of the form:

Warning: Assignment to x in soft scope is ambiguous because a global variable by the same name exists: x will be treated as a new local. Disambiguate by using local x to suppress this warning or global x to assign to the existing global variable.

This is because although global variables exist in all scopes, from Julia V1.0 on they are read-only in local scopes. This means that in order for this to work, access to global variables must be made explicit (otherwise it is read only in the local scope of the loop).

x = 0
for i in 1:10
   global x = x + i
end
println(x)

This is extremely annoying to say the least. But, wait it gets even more stupid. There is an exception to the rule, from the perspective of using syntax anyway. If we encapsulate the second piece of code inside a function, it works.

function sum(n)
   x = 0
   for i in 1:n
      x = x + i
   end
   return x
end

println(sum(10))

I don’t quite get why the same code acts differently in different circumstances, and it is likely even more confusing for the novice programmer. When x=0 is executed, x will become a new local variable in the body of the function. The for loop has its own inner local scope within the function scope. At the point where x=x+i occurs, x is already a local variable, so the assignment updates the existing x instead of creating a new local variable. So the same code in two places acts differently.

This is a good example of when language designers do something that just doesn’t make sense. Maybe it’s because there are so many people involved in the design of Julia. A global variable is by its very nature, global.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.