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.

4 Likes

Sorry for necroposting. Just be aware that this detects ‘toplevel scope’, but not ‘toplevel’ in the sense that “a module may be defined here”.
In particular:

println(@istoplevel) # true

let
  println(@istoplevel) # false
end

# but..
begin
  println(@istoplevel) # true
end

# and..
if true
   println(@istoplevel) # true
end
2 Likes