Julia version: 1.6.0
I recently had a bug in my code, after isolating the bug, it came down to a piece of code that looks like this:
function outer(n) function inner() n = n + 1 end inner() return n end println(outer(3))
My impression was that outer(3) should return 3, but it actually returns 4. Somehow the code in the inner() block assigns value 4 to the variable n outside of its scope.
To me this is very counter-intuitive. Is this a bug or intended behavior?
I tried a similar piece of code in Python:
def outer(n): def inner(): n = n + 1 inner() return n print(outer(3))
The python code results in an error:
UnboundLocalError: local variable 'n' referenced before assignment
It seems to me that Julia should throw an error like this as well. If the current behavior is correct and expected, I’d appreciate any insight as to the reason for this design.
After exploring this further, I found that Julia has completely different behavior from python when handling inner function definitions:
function outer() n1 = 1 function inner() n1 = 3 end inner() return n1 end println(outer())
But in python:
def outer(): n1 = 1 def inner(): n1 = 3 inner() return n1 print(outer())
So this confirms the previous observation that inner functions in Julia actually can assign values to variables outside of its scope. Is this intended behavior?