Can a package detect whether it was imported in the REPL vs inside another package?

Continuing the discussion from [ANN] UseAll.jl – Temporarily Demodularize Julia Code:

Even outside of the specific context of what makes sense for that UseAll package, that seems like an interesting question by itself.

Not really, no.

module MyPackage
function __init__()
    if !isinteractive()
        error("MyPackage is intended for interactive REPL use only.")
    end
end
end

This won’t prevent OtherPackage from accidentally making MyPackage a dependency, but at least would break OtherPackage’s CI, thus also preventing it’s registration.

2 Likes

You can check which module has a specific symbol in its namespace

julia> using UseAll

julia> filter(x -> isdefined(x, Symbol("@useall")), Base.loaded_modules_array())
2-element Vector{Module}:
 Main
 UseAll

AFAIK it’s guaranteed, that at least one binding is in the importing namespace. So in general you can loop through all names of all modules and check with parentmodule whether it’s a binding of your package.

However, this does not work in __init__, as the binding seems to be imported only after __init__ finishes, so you would need to use async with some sleep to do the check after __init__ finished.

With Base.active_repl, isinteractive and the above, I think you have all the building blocks to detect the specific conditions your package is operating in.

So while it seems to be possible, I think it somehow resembles COMEFROM :-).