How to test if a module is already imported?

974 views
Skip to first unread message

Matt Bauman

unread,
Apr 30, 2014, 6:09:35 PM4/30/14
to julia...@googlegroups.com
Is there a robust way to test if a Module has already been imported?  Some modules take a very long time to load, and in some contexts it might be nicer to check to see if the functionality is there before spending 30 seconds loading it and all its dependencies.

The naive :FooModule in names(Main) fails if I reference FooModule later in the same namespace.  I can get around that by adding another scope (like a macro or secondary function), but that's a bit of a pain.  Is there a better way?

julia> f() = :FooModule in names(Main) && (println("has FooModule"); FooModule.bar())
f (generic function with 1 method)

julia> f()
has FooModule
ERROR: FooModule not defined
 in f at none:1

Alessandro "Jake" Andrioni

unread,
Apr 30, 2014, 6:21:36 PM4/30/14
to julia...@googlegroups.com
A nicer hack would be to use the isdefined function:

julia> isdefined(:Stats)
false

julia> import Stats

julia> isdefined(:Stats)
true

Kevin Squire

unread,
Apr 30, 2014, 7:16:49 PM4/30/14
to julia...@googlegroups.com
Are you planning to load it if it isn't already loaded?  If so, there's no need to check--modules should only be loaded once, even if they're used/imported more than once.

Cheers,

   Kevin

Matt Bauman

unread,
Apr 30, 2014, 7:36:01 PM4/30/14
to julia...@googlegroups.com
No, my use case is to add some custom functionality to Gadfly within juliarc. Often I pre-compile Gadfly in userimg.jl, but not always. When it's not precompiled I don't particularly want to wait for it to load on every startup.

Pkg.on_load would be the perfect solution for this. But isdefined works great. Thanks Alessandro!

Reply all
Reply to author
Forward
0 new messages