Julia: include as a macro

Created on 6 Jun 2018  路  4Comments  路  Source: JuliaLang/julia

Ref. https://github.com/JuliaLang/julia/issues/19364#issuecomment-394957888

The idea would be that given a file bar.jl with contents y=5, one could do

function foo()
    local y
    @include "bar.jl"
    return y
end

and foo() would return 5, but not define a global variable y in the containing module. (Using the existing include function, foo() would define y globally and then fail because y is undefined in local scope.)

Most helpful comment

Also ref https://discourse.julialang.org/t/is-include-safe-to-use-inside-a-function/10867/6.

Such use (including a file into a non-global scope) in C/C++ is usually much harder to read so it is usually only needed in very specific cases for metaprogramming when the benefit of reducing code duplication outweight the decrease in readability. We have much better metaprogramming so it shouldn't be needed as much.

I'll also note that this syntax, when introduced, will cause at least two confusions for users that are looking for similar looking features,

  1. There's no way such a macro can support non global constant file names. foo(name) = @include name won't work.
  2. The body of foo will not change if bar.jl is modified, not even if foo() is recompiled and only if foo() is redefined.

All 4 comments

It's not needed in base so it can just go into a package?

Also ref https://discourse.julialang.org/t/is-include-safe-to-use-inside-a-function/10867/6.

Such use (including a file into a non-global scope) in C/C++ is usually much harder to read so it is usually only needed in very specific cases for metaprogramming when the benefit of reducing code duplication outweight the decrease in readability. We have much better metaprogramming so it shouldn't be needed as much.

I'll also note that this syntax, when introduced, will cause at least two confusions for users that are looking for similar looking features,

  1. There's no way such a macro can support non global constant file names. foo(name) = @include name won't work.
  2. The body of foo will not change if bar.jl is modified, not even if foo() is recompiled and only if foo() is redefined.

I think this would be a really marginal feature. It's hard to imagine this being the right solution for anything.

Right, it's not like I have a compelling use case for this. I just vaguely remembered seeing a question similar to #19364 and wondered whether this might be useful. Consensus seems to be it's not.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tkoolen picture tkoolen  路  3Comments

iamed2 picture iamed2  路  3Comments

ararslan picture ararslan  路  3Comments

felixrehren picture felixrehren  路  3Comments

Keno picture Keno  路  3Comments