Is there a way to determine whether code is toplevel?

I’m looking for a hypothetical @istoplevel, presumably a macro, which could work like this:

module Foo
@istoplevel() # true
end
julia> @istoplevel() # true
function foo()
    @istoplevel() # false
end

Does anything like this exist or can it be constructed?

2 Likes

Yes, you can set a gensym variable and test if it is indeed set on __module__.

2 Likes

Ha! That works, thanks.

macro istoplevel()
    canary = gensym("canary")
    quote
        $(esc(canary)) = true
        Base.isdefined($__module__, $(QuoteNode(canary)))
    end
end

I think that might be OK for me, but would still be interested in if there’s a more direct solution.

3 Likes