Macros not imported within blocks

I find that macros are not imported if the package defining the macros are imported within a block. For example, importing Printf and using the macro @printf by

if true
    using Printf
    @printf("test")
end

produces the following error:

ERROR: LoadError: UndefVarError: @printf not defined

The same error is generated when if true ... end block is replaced with begin ... end block.

The same error is produced for packages other than Printf. For example,

begin
    using StaticArrays
    @SVector(zeros(3))
end

produces the following error:

ERROR: LoadError: UndefVarError: @SVector not defined

Non-macros are imported fine. For example,

begin
    using StaticArrays
    SVector(1,2,3)
end

runs fine.

I observe the same behavior in Julia version 1.0 through 1.5. Why is this happening? Is there a way to import macros properly within code blocks? I would like to import some packages within if ... end blocks because importing packages takes time: I don’t want to import them when they are not needed.

Macros operates per top level block. You can only use the macro in the following block.

1 Like