-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
Description
Example 1
This came up with a student who upgraded from 0.6 to 1.0 directly, so never even got a chance to see a deprecation warning, let alone find an explanation for new behavior:
julia> beforefor = true
true
julia> for i in 1:2
beforefor = false
end
julia> beforefor # this is surprising bit
true
julia> beforeif = true
true
julia> if 1 == 1
beforeif = false
end
false
julia> beforeif # Another surprise!
false
julia> function foo()
infunc = true
for i in 1:10
infunc = false
end
@show infunc
end
foo (generic function with 1 method)
julia> foo() # "I don't get this"
infunc = false Example 2
julia> total_lines = 0
0
julia> list_of_files = ["a", "b", "c"]
3-element Array{String,1}:
"a"
"b"
"c"
julia> for file in list_of_files
# fake read file
lines_in_file = 5
total_lines += lines_in_file
end
ERROR: UndefVarError: total_lines not defined
Stacktrace:
[1] top-level scope at ./REPL[3]:4 [inlined]
[2] top-level scope at ./none:0
julia> total_lines # This crushs the students willingness to learn
0I "get" why this happens in the sense that I think I can explain, with sufficient reference to the arcana in the manual about what introduces scopes and what doesn't, but I think that this is problematic for interactive use.
In example one, you get a silent failure. In example two, you get an error message that is very there-is-no-spoon. Thats roughly comparable to some Python code I wrote in a notebook at work today.
I'm not sure what the rules are in Python, but I do know that generally you can't assign to things at the global scope without invoking global. But at the REPL it does work, presumably because at the REPL the rules are different or the same logic as if they were all are in the scope of function is applied.
I can't language-lawyer the rules enough to propose the concrete change I would like, and based on Slack this isn't even necessarily perceived as an issue by some people, so I don't know where to go with this except to flag it.
Cross-refs:
#19324
https://discourse.julialang.org/t/repl-and-for-loops-scope-behavior-change/13514
https://stackoverflow.com/questions/51930537/scope-of-variables-in-julia