Is importing module is allowed inside @static?

It seems allowed but somehow limited in what it allows.

I tried:

use_sklearn = true

@static if use_sklearn
    using ScikitLearn
    @sk_import linear_model: LogisticRegression
else
    using GLM
end

, which produces

ERROR: LoadError: LoadError: UndefVarError: @sk_import not defined

The code only compiles when using ScikitLearn is placed outside and above @static block:

using ScikitLearn

use_sklearn = true

@static if use_sklearn
    @sk_import linear_model: LogisticRegression
else
    using GLM
end

Yes it is.

What you see errors for the same reason it errors without the @static, the macro needs to be evaluated BEFORE the toplevel expression (i.e. if ... or @static if ...) can run so the macro is evaluated BEFORE you imported the module. Repeat if twice, first with import and second time with the macro should work. Note that for the import/using you don’t need @static. You only need it for the @sk_import since it’s a macro.

4 Likes

Oh understood. So any macro in a code block is evaluated (or expanded) before anything else than itself. That makes sense. It should be very helpful to new comers if that is mentioned in the manual (seems not). The double ifs or @static ifs work fine. Thanks a lot!