Including modules inside blocks vs non-top-level modules

Yes, exactly: include evaluates the file contents in the global scope of the current module, i.e. as if it was written in the top-level of the current module. If you know about C / C++, maybe it helps to emphasize that – although their names are very close – Julia’s include() function is not akin to C’s #include pre-processing macro in this respect.

If you want the module declaration to work from an if / else clause, you can wrap it inside @eval, which will in this case have more or less the same effect as include: evaluate the statement in the global scope of the current module:

julia> if true
           module Foo
              println("HELLO DIRECT")
           end
       end
ERROR: syntax: "module" expression not at top level
Stacktrace:
 [1] top-level scope
   @ REPL[2]:1
julia> if true
           @eval module Foo
              println("HELLO DIRECT")
           end
       end
HELLO DIRECT
Main.Foo
2 Likes