The reason as Cedric points out is that the do block syntax is just sugar
for an anonymous function body. There is a plan to provide a more
convenient mechanism for ensuring finalization: #7721
<https://github.com/JuliaLang/julia/issues/7721>. So, pending syntax
debating, you'd write this instead:

fd = open(file)!
a = read(fd, ...)
b = read(fd, ...)
# finalize(fd) called when the scope ends


This would significantly reduce the number of situations where the do block
syntax is used for straight-line code, which I think largely eliminates
this issue.


On Mon, Jun 20, 2016 at 10:35 AM, Cedric St-Jean <[email protected]>
wrote:

> I'm not sure why assignments are local, but I'd guess that it's for
> consistency. function foo(x, y) ... end is syntactic sugar for foo =
> (x,y)->..., and likewise do syntax is also sugar for creating a function
> and passing it as the first argument. Since
>
> function foo(x)
>     a = x
> end
>
> does not modify foo's parent scope (the global scope), it seems reasonable
> that local functions (do blocks) shouldn't modify their parent scope
> either. Here are other ways of writing the code you quoted:
>
> local a, b
> open(file) do fd
>  a = read(fd, ...) # will modify a and b in the parent scope
>  b = read(fd, ...)
> end
>
> comprehension = map(collection) do i
>   ## compute element[i]
>   element
> end
>
> Best,
>
> Cédric
>
>
> On Monday, June 20, 2016 at 7:54:10 AM UTC-4, David van Leeuwen wrote:
>>
>> Hello,
>>
>> I regularly make the mistake described here
>> https://groups.google.com/d/msg/julia-users/UyCSm5Shyww/Udt67boT3CsJ,
>> i.e., i write
>>
>> open(file) do fd
>>   a = read(fd, ...)
>>   b = read(fd, ...)
>> end
>> ## a and b undefined.
>>
>> I get that the solution is
>>
>> a, b = open(file) do fd
>> ...
>>
>> Great.  I understand that you would want `fd` to be local, is this the
>> reason that every assignment is local?
>>
>> If `a, b = open() do ... end` is the recommended way of dealing with
>> this, I wonder if this approach could generalize to the for-block
>>
>> comprehension = for i in collection
>>    ## compute element[i]
>>    element
>> end
>>
>> as a multiline alternative to the [element for i in collection] syntax.
>>
>> Cheers,
>>
>> ---david
>>
>

Reply via email to